I am struggling to define e.g. std::ops::Add for my generic type ( Custom say) where i want to be able to add e.g. a f64 both from the left and the right.
I.e I would like:
let c: Custom<T> = ...;
let a = 1.0;
return a + c + a;
to work - but cannot see how to implement that. See for example Rust Playground for a simplified example of what does not work.
Any pointer appreciated.
a + b is syntactic sugar for
A::add(a, b), so
b + a always calls the
add() method on
B. Thus, you'd have to blanket-impl
Add<Custom<T>> for T, but that isn't allowed due to coherence.
Note that this doesn't require the above impl! Addition associates to the left, so if
<A as Add<C>>::Output = A, then this will work with the above unilateral impl and
impl Add<Custom<T>> for Custom<T>: Playground.
Thanks and I see you point with a + c + a actually working - bad specification by me.
But that means then that it's impossible for me to get plain a + c to work? (as well as e.g 2.0*c etc.)
In a generic setting, it's indeed not possible. You can spell out some concrete types instead.