How to implement the trait?

How to make a trait implementation for the type specified by the template?

use std::ops::{Add};

trait Vector<T> {}

impl<V, T> Add for V where V: Vector<T> {}

Errors:

   Compiling playground v0.0.1 (/playground)
error[E0207]: the type parameter `T` is not constrained by the impl trait, self type, or predicates
 --> src/lib.rs:5:9
  |
5 | impl<V, T> Add for V where V: Vector<T> {}
  |         ^ unconstrained type parameter

error: aborting due to previous error

For more information about this error, try `rustc --explain E0207`.
error: could not compile `playground`.

To learn more, run the command again with --verbose.

You can't do this because a single type might implement Vector<T> for multiple values of T, so Add would not be able to determine which Vector<T> impl to use. Consider using an associated type instead, which changes it so a type can only implement Vector once.

trait Vector {
    type Scalar;
}

impl<V> Add for V
where
    V: Vector,
    V::Scalar: Add,
{
    ...
}
2 Likes

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.