使用特征对象时,使用rust 具有特征绑定(bind)的泛型类型

标签 rust trait-objects

trait MyTrait {
    fn my_f(&self) ;
}

struct A {}
struct B {}

impl MyTrait for A {
    fn my_f(&self) {
        println!("A.my_f()");
    }
}
impl MyTrait for B {
    fn my_f(&self) {
        println!("B.my_f()");
    }
}

struct MyList<T: MyTrait> {
    list: Vec<T>
}

fn main() {
    let list = MyList {
        list: vec![
            Box::new(A{}),
            Box::new(B{})
        ]
    };
}

我关注了这篇文章,Using Trait Objects That Allow for Values of Different Types

根据这篇文章:

This restricts us to a Screen instance that has a list of components all of type Button or all of type TextField. If you’ll only ever have homogeneous collections, using generics and trait bounds is preferable because the definitions will be monomorphized at compile time to use the concrete types.

On the other hand, with the method using trait objects, one Screen instance can hold a Vec that contains a Box as well as a Box. Let’s look at how this works, and then we’ll talk about the runtime performance implications.

但是这段代码无法编译。

最佳答案

仔细阅读有关 Defining a Trait for Common Behavior 的部分。它定义了Screen在 list 17-4 中,带有 Vec<Box<dyn Draw>> :

pub struct Screen {
    pub components: Vec<Box<dyn Draw>>,
}

然后它说:

we could have defined the Screen struct using a generic type and a trait bound as in Listing 17-6

强调条件“可以”。然后它继续解释为什么使用泛型类型和特征绑定(bind)不起作用:

This (1) restricts us to a Screen instance that has a list of components all of type Button or all of type TextField.

[…]

On the other hand, with the method using trait objects (2), one Screen instance can hold a Vec<T> that contains a Box<Button> as well as a Box<TextField>.

(1) 使用泛型类型和特征绑定(bind)

(2) 即 Box<dyn<Draw>>

关于使用特征对象时,使用rust 具有特征绑定(bind)的泛型类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74384687/

相关文章:

rust - 尝试使用 slice in rust 实现构建器功能

rust - Rc<Trait> 到 Option<T>?

generics - Rust:从(仅)<T> 不同的函数返回通用结构

rust - 为什么将 Option::map 用于 Box::new 特征对象不起作用?

rust - 有没有办法确定 VTable 中每个特征方法的偏移量?

generics - 是否可以自动实现将一个特征对象转换为另一个特征对象的特征?

rust - 结果得到意外的类型参数

windows - 从其他子模块访问子模块的函数

types - 如何键入注释宏的返回值?