【问题标题】:Cannot return Option<associated type> because associated type is not sized无法返回 Option<关联类型>,因为关联类型未调整大小
【发布时间】:2017-10-24 03:32:57
【问题描述】:

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

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;
}

我肯定在这里遗漏了一些重要的东西。

【问题讨论】:

标签: rust traits associated-types


【解决方案1】:

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

另请参阅documentation for Sized

【讨论】:

    【解决方案2】:

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

    required by `std::option::Option`
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-29
      • 1970-01-01
      • 2022-01-04
      • 2019-08-24
      相关资源
      最近更新 更多