【发布时间】: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;
}
我肯定在这里遗漏了一些重要的东西。
【问题讨论】:
-
哦,我刚刚注意到,当我指定
Sized而不是?Sized时,我的NotWorking示例正在工作。 -
?Sized表示无需调整大小:doc.rust-lang.org/std/marker/trait.Sized.html
标签: rust traits associated-types