我试图更好地理解Any
特质,发现它有一个用于特质本身的impl
块。我不理解这个结构的目的,甚至不知道它是否有一个特定的名称。
我对“普通”特质方法和在impl
块中定义的方法进行了一些小实验:
trait Foo {
fn foo_in_trait(&self) {
println!("in foo")
}
}
impl dyn Foo {
fn foo_in_impl(&self) {
println!("in impl")
}
}
impl Foo for u8 {}
fn main() {
let x = Box::new(42u8) as Box<dyn Foo>;
x.foo_in_trait();
x.foo_in_impl();
let y = &42u8 as &dyn Foo;
y.foo_in_trait();
y.foo_in_impl(); // May cause an error, see below
}
从这个有限的实验来看,似乎在Editor's note
In versions of Rust up to and including Rust 1.15.0, the line
y.foo_in_impl()
causes the error:error: borrowed value does not live long enough --> src/main.rs:20:14 | 20 | let y = &42u8 as &Foo; | ^^^^ does not live long enough ... 23 | } | - temporary value only lives until here | = note: borrowed value must be valid for the static lifetime...
This error is no longer present in subsequent versions, but the concepts explained in the answers are still valid.
impl
块中定义的方法比在trait
块中定义的方法更加受限制。很可能有一些额外的东西通过这种方式解锁,但我还不知道是什么!^_^《Rust编程语言》中关于traits和trait objects的章节没有提到这一点。在搜索Rust源代码时,似乎只有
Any
和Error
使用了这个特定的功能。在我查看过源代码的一些crate中,我没有看到使用这个功能的情况。