Home > Software engineering >  Implementing a trait for anything that implements a trait?
Implementing a trait for anything that implements a trait?

Time:09-24

I want to implement the trait Add trait for anything that implements Into<u64>.I tried this,

impl<T> Add<Into<T>> for Sequence {
    type Output = Self;
    fn add(self, rhs: T) -> Self::Output {
      todo!();
    }
}

This gives me two errors,

doesn't have a size known at compile-time
= help: the trait `Sized` is not implemented for `(dyn Into<T>   'static)`

And,

`Into` cannot be made into an object
= note: the trait cannot be made into an object because it requires `Self: Sized`
= note: for a trait to be "object safe" it needs to allow building a vtable to allow the call to be resolvable dynamically; for more information visit <https://doc.rust-lang.org/reference/items/traits.html#object-safety>

I've tried replacing that with,

impl<T> Add<dyn Into<T>   'static   Sized> for Sequence {

But I'm still getting errors

doesn't have a size known at compile-time
= help: the trait `Sized` is not implemented for `(dyn Into<T>   'static)`
note: required by a bound in `Add`

What's the right syntax here, I'm going down a rabbit hole?

CodePudding user response:

The syntax you want is,

impl<T: Into<u64>> Add<T> for Sequence {
  type Output = Self;
  fn add(self, rhs: T) -> Self::Output {
  ...
}

This will implement Add<T> for all T that implement Into<u64>

I opened up a bug to get the compiler to provide more guidance

  • Related