【问题标题】:Implementing a trait for anything that implements a trait?为任何实现特征的东西实现特征?
【发布时间】:2021-11-14 17:31:54
【问题描述】:

我想为任何实现Into<u64>的东西实现特征Add。我试过这个,

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

这给了我两个错误,

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

还有,

`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>

我尝试将其替换为,

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

但我仍然遇到错误

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`

这里的正确语法是什么,我要陷入困境?

【问题讨论】:

    标签: generics rust syntax traits implementation


    【解决方案1】:

    你想要的语法是,

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

    这将为所有实现Into&lt;u64&gt;T实现Add&lt;T&gt;

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-08
      • 1970-01-01
      • 2015-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-14
      相关资源
      最近更新 更多