How to implement a symmetric operation?

There is some definition of structure Matrix

pub struct Matrix<'a, T> {

and implementation the operator of multiplying the matrix by a number: Matrix * k

impl<'a, T> ops::Mul<T> for Matrix<'a, T> {

but trying to implement a symmetric operation k * Matrix results in a compilation error

impl<'a, T> ops::Mul<Matrix<'a, T>> for T {

Tell me how to do it right?

The problem is that I'm technically allowed to write this:

impl<T> ops::Mul<T> for MyType { ... }

Unfortunately, if someone links my crate and your crate into the same application, and then multiplies MyType by Matrix<MyType>, then both impl blocks will be applicable. There's only ever supposed to be one valid impl block for a given trait and type pair, but both of our crates are supposed to be compiled separately and then linked at the end, so the compiler can't just check. It could fail at link time, but then that would allow people to accidentally create crates that cannot be included in the same application, which would be bad for Rust's library ecosystem.

So Rust has to impose some general rules on what you're allowed to implement traits for, mostly no implementing another crate's trait for another crate's type. Unbound type T is considered "another crate's type", and Mul is definitely another crate's trait.

For more information,

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.