我正在使用 Rust 1.31 以前的版本为引用类型实现一个 trait。当我告诉 Rust 我要为哪种引用类型实现 trait 时,为什么它需要一个明确的生命周期?
这里有一个简单的例子。一个名为 Inches 的结构体,为 &Inches 实现 Add trait,并编写了一个使用该实现的函数。
初始示例: (Rust playground link)
编译失败,出现以下错误:
我加入了缺失的生命周期说明符(仍无法编译)。
编译错误:
我在
This, finally, compiles correctly.
我的问题
为什么在 "impl Add for &Inches" 中的 "&Inches" 被认为缺少生命周期说明符?通过告诉编译器这个 Add 方法是针对具有某个未指定非静态生命周期 'b 的 "&Inches",并且从未在其他任何地方引用该生命周期,解决了什么问题?
这里有一个简单的例子。一个名为 Inches 的结构体,为 &Inches 实现 Add trait,并编写了一个使用该实现的函数。
初始示例: (Rust playground link)
use std::ops::Add;
struct Inches(i32);
// this would work: impl<'b> Add for &'b Inches
impl Add for &Inches {
type Output = Inches;
fn add(self, other: &Inches) -> Inches {
let &Inches(x) = self;
let &Inches(y) = other;
Inches(x + y)
}
}
// lifetime specifier needed here because otherwise
// `total = hilt + blade` doesn't know whether `total` should live
// as long as `hilt`, or as long as `blade`.
fn add_inches<'a>(hilt: &'a Inches, blade: &'a Inches) {
let total = hilt + blade;
let Inches(t) = total;
println!("length {}", t);
}
fn main() {
let hilt = Inches(10);
let blade = Inches(20);
add_inches(&hilt, &blade);
}
编译失败,出现以下错误:
error: missing lifetime specifier [E0106]
impl Add for &Inches {
^~~~~~~
我加入了缺失的生命周期说明符(仍无法编译)。
// was: impl Add for &Inches {
impl Add for &'b Inches {
...
}
编译错误:
error: use of undeclared lifetime name `'b` [E0261]
impl Add for &'b Inches {
我在impl
上声明了生命周期(现在已经编译通过)
// was: impl Add for &'b Inches {
impl<'b> Add for &'b Inches {
...
}
This, finally, compiles correctly.
我的问题
为什么在 "impl Add for &Inches" 中的 "&Inches" 被认为缺少生命周期说明符?通过告诉编译器这个 Add 方法是针对具有某个未指定非静态生命周期 'b 的 "&Inches",并且从未在其他任何地方引用该生命周期,解决了什么问题?