这个trait 定义可以很好地编译:
trait Works {
fn foo() -> Self;
}
然而,这会导致以下错误:
trait Errors {
fn foo() -> Option<Self>;
}
error[E0277]: the size for values of type `Self` cannot be known at compilation time
--> src/lib.rs:6:5
|
6 | fn foo() -> Option<Self>;
| ^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
|
= help: the trait `std::marker::Sized` is not implemented for `Self`
= note: to learn more, visit <https://doc.rust-lang.org/book/second-edition/ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait>
= help: consider adding a `where Self: std::marker::Sized` bound
= note: required by `std::option::Option`
有了: Sized
个supertrait绑定,它就可以工作了.
我知道,Self
种类型的trait 并不是自动地就一定是Sized
种.我知道Option<Self>
不能被返回(通过堆栈),除非它被调整大小(反过来,需要调整Self
的大小).然而,Self
作为返回类型也是一样的,对吗?它也不能存储在堆栈上,除非大小合适.
Why doesn't the first trait definition already trigger that error?
(100 is related, but it doesn't answer my exact question – unless I didn't understand it.)