在Rust 1.3.0中,Deref
trait在文档中有以下签名:
pub trait Deref {
type Target: ?Sized;
fn deref(&'a self) -> &'a Self::Target;
}
我将实现它,而不命名生命周期,因为它们无论如何都会被忽略.然而,在docs example人中,情况是这样的:
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);
}
如果使用生命周期 为'a
,则使用生命周期 为'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 | | }
| |_^
这让我困惑.该方法的签名与文档中的签名没有区别.此外,我认为在impl上指定life参数与直接在方法上指定life参数的区别仅在参数的范围内,因此它可以在整个impl块中使用,而不仅仅是在方法中使用.我错过了什么?