无法返回选项<associated type =“”>,因为关联的类型未调整大小

时间:2017-10-24 03:32:57

标签: rust traits associated-types

我不明白为什么这段代码无法编译:

fn main() {}

trait NotWorking {
    // The associated type `Bar` must be sized
    type Bar: ?Sized;

    // Why does the compiler complain that Self::Bar is not sized?
    // I have a trait bound that says it is!
    fn notwoking() -> Option<Self::Bar>;
}

我确实有一个约束,必须调整关联​​类型Bar的大小,但编译器仍然抱怨它未被大小写:

error[E0277]: the trait bound `<Self as NotWorking>::Bar: std::marker::Sized` is not satisfied
  --> src/main.rs:17:5
   |
17 |     fn notwoking() -> Option<Self::Bar>;
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `<Self as NotWorking>::Bar` does not have a constant size known at compile-time
   |
   = help: the trait `std::marker::Sized` is not implemented for `<Self as NotWorking>::Bar`
   = help: consider adding a `where <Self as NotWorking>::Bar: std::marker::Sized` bound
   = note: required by `std::option::Option`

我玩了一点,尝试使它工作,并且惊讶于这是有效的(因为我们不能返回一个未经过类型化的类型,我期待它失败):

fn main() {}

trait Working {
    type Bar;

    // Why does this work?
    // I would expect the compiler to complain the Self::Bar is not sized
    fn woking() -> Self::Bar;
}

我肯定错过了一些重要的事情。

2 个答案:

答案 0 :(得分:2)

你的第二个例子是正确的。声明带有Sized边界的泛型参数的方法是不指定任何显式边界。 Sized的特殊之处在于默认情况下它被隐式添加为泛型参数的绑定,因为事物不是Sized是相对不常见的。如果您不希望通用参数在编译时具有已知大小,则可以remove this implicit bound by writing ?Sized

另请参阅documentation for Sized

答案 1 :(得分:1)

答案在最后一个字符串中:

required by `std::option::Option`

我不是专家,但我想编译器需要有关类型大小的信息才能知道如何在内存中布置枚举Bar的变体类型Option