【发布时间】:2016-03-30 01:40:58
【问题描述】:
在尝试更好地理解 Any 特征时,我看到了 has an impl block for the trait itself。我不明白这个构造的目的,或者即使它有一个特定的名称。
我用“正常”特征方法和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
}
编者注
在 Rust 1.15.0 及之前的版本中,该行
y.foo_in_impl()导致错误: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...此错误在后续版本中不再存在,但 答案中解释的概念仍然有效。
从这个有限的实验来看,impl 块中定义的方法似乎比trait 块中定义的方法更严格。这样做可能会解锁一些额外的东西,但我只是还不知道它是什么! ^_^
traits 和 trait objects 上的 Rust 编程语言 部分没有提及这一点。搜索 Rust 源代码本身,似乎只有 Any 和 Error 使用此特定功能。在我查看源代码的少数 crate 中,我没有看到它使用过。
【问题讨论】:
-
非常有趣的问题!特征块中的
Self是Foo和impl块中的Self是Foo + 'static...