代码之家  ›  专栏  ›  技术社区  ›  hellow Adolfo Casari

如何在集合中插入大小特征

  •  3
  • hellow Adolfo Casari  · 技术社区  · 6 年前

    Playground

    #[derive(Default)]
    struct Bar;
    
    #[derive(Default)]
    struct Baz;
    
    fn main() {
        let mut vec = Vec::<Box<dyn Default>>::new();
    //                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `std::default::Default` cannot be made into an object
        vec.push(Box::new(Bar));
        vec.push(Box::new(Baz));
    }
    

    Default 是一种体型特征,也就是说你 cannot convert it to a trait object .

    Vec (或其他收藏品)?

    1 回复  |  直到 6 年前
        1
  •  5
  •   Boiethios    6 年前

    由于对象安全规则,您不能执行此操作。这个规则说,方法返回具体类型本身的特征不能成为特征对象。原因是trait对象应该知道具体的类型。

    而且,这个特性没有方法(一个函数 self ),因此没有必要从中创建trait对象。

    here , there 在这里面 blog article

    另见 this question .


    这个规则非常直观:您希望代码做什么?

    #[derive(Default)]
    struct Bar;
    
    #[derive(Default)]
    struct Baz;
    
    fn main() {
        let mut vec = Vec::<Box<dyn Default>>::new();
        vec.push(Box::new(Bar));
        vec.push(Box::new(Baz));
    
        vec.first().unwrap()::new();
        // Whatever the syntax should be, what do you expect this to return?
        // This type cannot be know at compile time.
    }