Overload function return type in trait

I'm trying to write a function in a trait that either outputs a scalar T or a NdArray ArrayBase<ViewRepr<&T>, I>. I thought of the workaround using the one-to-one mapping between T and ArrayBase<ViewRepr<&T>, Ix0>, but it does not work.

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 any better workaround, more in tune with Rust spirit? My goal is to write idiomatic Rust. My current solution is to create two different traits, one implementing a function outputting a scalar and another the array.

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

Many thanks in advance

Rust doesn't support ad-hoc overloading, but does allow principled overloading via traits.

So if you want to have a foo that can return multiple different types that the caller can pick between, then you can do something like

trait Foo<T> {
    fn foo(&self) -> T;

If instead you want to have foo return different types when called on different types (where the type gets to pick, rather than the caller), then you want

trait Foo {
    type Output;
    fn foo(&self) -> Self::Output;

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.