Implement Add for non-copy rhs by reference

Say I have a struct PrimitiveArray<T> that is roughly translated to an array, say stored as Vec<T>.

Is there a way to declare the std::ops::Add so that users can write a + b, but where b is not taken by value? So far I was only able to make it a + &b:

impl<T> std::ops::Add<&PrimitiveArray<T>> for PrimitiveArray<T>
    T: NativeArithmetics + Add<Output = T>,
    type Output = Self;

    fn add(mut self, rhs: &Self) -> Self::Output {
        binary(&mut self, rhs, |x, y| x + y);
  • is there a trait that I can use to auto-convert so that users can write a + b?
  • Would this be a good idea (instead of making it explicit that the op is being called by ref on the right hand side?

Nope. You can implement it for owned RHS too, but I would not recommend - it is too easy to misuse. std types do not do that either (for example String in std::string - Rust)

What would be a good idea? To have such trait?

1 Like

In Rust, as far as I can tell, it is never a good idea to de-reference automatically.

1 Like

Ah, that was what I was looking for - an authoritative example implementation - std::String does indeed make it explicit, so we should it too! Thanks!

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.