Deref
trait 在文档中的签名如下:pub trait Deref {
type Target: ?Sized;
fn deref(&'a self) -> &'a Self::Target;
}
我会实现它而不命名生命周期,因为它们最终会被省略。然而,在文档示例中,它看起来像这样:
use std::ops::Deref;
struct DerefExample<T> {
value: T
}
impl<T> Deref for DerefExample<T> {
type Target = T;
fn deref<'a>(&'a self) -> &'a T {
&self.value
}
}
fn main() {
let x = DerefExample { value: 'a' };
assert_eq!('a', *x);
}
这很好地实现了功能,但如果我在impl上指定lifetime参数
'a
而不是在方法上指定,则会出现以下问题:struct DerefExample<T> {
value: T
}
impl<'a, T> Deref for DerefExample<T> {
type Target = T;
fn deref(&'a self) -> &'a T {
&self.value
}
}
我得到了以下错误:
error[E0308]: method not compatible with trait
--> src/main.rs:10:5
|
10 | / fn deref(&'a self) -> &'a T {
11 | | &self.value
12 | | }
| |_____^ lifetime mismatch
|
= note: expected type `fn(&DerefExample<T>) -> &T`
found type `fn(&'a DerefExample<T>) -> &'a T`
note: the anonymous lifetime #1 defined on the method body at 10:5...
--> src/main.rs:10:5
|
10 | / fn deref(&'a self) -> &'a T {
11 | | &self.value
12 | | }
| |_____^
note: ...does not necessarily outlive the lifetime 'a as defined on the impl at 7:1
--> src/main.rs:7:1
|
7 | / impl<'a, T> Deref for DerefExample<T> {
8 | | type Target = T;
9 | |
10 | | fn deref(&'a self) -> &'a T {
11 | | &self.value
12 | | }
13 | | }
| |_^
我感到困惑。这个方法的签名与文档中的方法没有什么不同。此外,我认为在实现或直接在方法上指定生命周期参数之间的区别仅在于参数的范围,因此它可以在整个实现块中使用而不仅仅是方法中。我在这里错过了什么吗?