如何使我自己的适配器方法能够使用特征对象?

She*_*ter 6 traits rust

我有一个特性,其中包含使用该方法的"适配器方法":

struct Bar<T>(T);

trait Foo {
    fn make_bar(self) -> Bar<Self>
    where
        Self: Sized,
    {
        Bar(self)
    }
}

impl Foo for u8 {}
impl Foo for bool {}
Run Code Online (Sandbox Code Playgroud)

这是模仿的Iterator.当我使用Box<Iterator>,我仍然可以调用Iterator适配器方法类似mapfilter:

fn main() {
    let a = vec![1, 2, 3];
    let b: Box<Iterator<Item = u8>> = Box::new(a.into_iter());
    let c = b.map(|x| x * 2);
    for z in c {
        println!("{}", z)
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,我定义的方法不能以相同的方式工作:

fn main() {
    let a: Box<Foo> = Box::new(42);
    a.make_bar();
}
Run Code Online (Sandbox Code Playgroud)

这失败了,错误

error[E0277]: the trait bound `Foo: std::marker::Sized` is not satisfied
  --> src/main.rs:18:7
   |
18 |     a.make_bar();
   |       ^^^^^^^^ `Foo` does not have a constant size known at compile-time
   |
   = help: the trait `std::marker::Sized` is not implemented for `Foo`
Run Code Online (Sandbox Code Playgroud)

Foo没有大小的绝对正确- 这是一个特点.但是,据我所知,Box<Foo> 应该有一个尺寸.Iterator与我的代码有什么不同?

Chr*_*gan 6

因为Iterator对象是安全的,所以trait对象Iterator实现Iterator.

因为impl<I: Iterator + ?Sized> Iterator for Box<I>,盒装特征对象Box<Iterator>实现了Iterator.

因此,在你的情况下,解决方案是实现FooBox<Foo>.这可以是通用的,如Iterator's(impl<T: ?Sized + Foo> Foo for Box<T> { }),也可以是特定的(impl Foo for Box<Foo> { }).