首页 > 解决方案 > trait impl 的委派只能在夜间进行?

问题描述

我想将特征的实现委托Foo给(单个元素)容器的内容Bar,只有当它的通用内容已经实现FooBar<T: Foo>)时。

pub trait Foo {
    fn foo(&self) -> u8;
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialOrd, Ord, PartialEq, Eq)]
pub struct Bar<T> {
    wrapped: T
}

impl Foo for Bar<T: Foo> {
    fn foo(&self) -> u8 {
        self.wrapped.foo()
    }
}

结果是:

error[E0658]: associated type bounds are unstable
  --> /home/fadedbee/test.rs:26:18
   |
26 | impl Foo for Bar<T: Foo> {
   |                  ^^^^^^
   |
   = note: see issue #52662 <https://github.com/rust-lang/rust/issues/52662> for more information
   = help: add `#![feature(associated_type_bounds)]` to the crate attributes to enable

这只能在夜间进行,还是我只是使用了错误的语法?

标签: rusttraits

解决方案


只是一个小的语法差异。

impl<T : Foo> Foo for Bar<T> {
  fn foo(&self) -> u8 {
    self.wrapped.foo()
  }
}

impl需要引入类型变量,然后我们Bar. 以上等价于更详细的

impl<T> Foo for Bar<T> where T : Foo {
  fn foo(&self) -> u8 {
    self.wrapped.foo()
  }
}

在任何一种情况下,都会impl引入类型变量。


推荐阅读