Function return type overloading in Trait

Viewed 75

I'm writing a function in a trait that either outputs a scalar T or a NdArray ArrayBase<ViewRepr<&T>, I>. I know that Rust does not support function overloading. I've come across different solutions like outputting a tuple (first element being a scalar, and second being an array). Do you find this solution idiomatic in Rust? Or do you know a better workaround?

My current solution is to create two different traits, one implementing a function outputting a scalar and another function in another trait outputting an array.

I'm looking for a better solution since it would significantly alleviate my codebase.

1 Answers

You can use an associated type in the trait for the output:

pub trait MyTrait {
    type Output;

    fn execute(&self) -> Self::Output;
}

...
struct MyCompute;

impl MyTrait for MyCompute {
    type Output = u64;

    fn compute(&self) -> Self::Output { ... }
}
Related