考虑以下代码:
pub trait Trait {
fn foobar(&self) {
baz(self)
}
}
fn baz<T: Trait>(t: &T) {
println!("asdfadsf");
}
请注意,baz
特意留在了特征之外:这是一个实现细节,不应泄漏到模块外部。上面的代码无法编译,并出现以下错误:
error[E0277]: the size for values of type `Self` cannot be known at compilation time
--> src/lib.rs:3:9
|
3 | baz(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-sized>
= help: consider adding a `where Self: std::marker::Sized` bound
note: required by `baz`
--> src/lib.rs:7:1
|
7 | fn baz<T: Trait>(t: &T) {
| ^^^^^^^^^^^^^^^^^^^^^^^
为什么baz
关心T
的大小?它以参考为参数。无需了解所引用对象的大小。当然,我可以将+ ?Sized
粘贴到baz
上绑定的特征上,但是为什么需要它,以及Rust-y处理该问题的方法是什么?