Implement traits for values or also for references?

Hi,

how do you decide whether a trait should only be implemented for the value type or also for references?

To keep it simple: imagine a linear algebra library that implements a Vector type. Should the Add trait be implemented only for the type Vector or also for &Vector and &mut Vector?

Are there general guidelines or special cases to consider?

Thanks in advance.

Probably for all 3 in the case of Vector and the Add trait.

I think this mostly comes down to how the types in question will be used. A few considerations that spring to mind:

  1. if the type is not Clone/Copy, then majority of code will be using references to not transfer ownership back and forth. The trait should then definitely be implemented for references.
  2. if the type will be used in some generic context, only a reference may be available. For example, iterating over a borrowed collection.
  3. if the type is Copy, then only supporting the trait for a value isn't a big deal. However, it may interfere with ergonomics in some cases.
1 Like

Thanks! Does make sense to me.