【发布时间】:2015-08-05 15:14:00
【问题描述】:
我正在使用早于 1.31 的 Rust 实现引用类型的特征。 当我告诉 Rust 为什么引用类型实现 trait 时,为什么 Rust 需要明确的生命周期?
这是一个简单的例子。一个结构Inches,一个实现
Add 特征为 &Inches,以及使用该实现的函数。
初始示例
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 {
...
}
这终于可以正确编译了。
我的问题
为什么
impl Add for &Inches中的&Inches被认为缺少一个 寿命说明符?告诉编译器解决什么问题 这个 Add 方法适用于&Inches,带有一些未指定的非静态 生命周期'b,然后在任何地方都不要提及那个生命周期 还有吗?
【问题讨论】:
-
'b 的生命周期在 + 操作中作为 'a 提供(当然是在编译时),允许编译器强制/确保 'b 到 'a 的生命周期要求,并且然后到main中的变量,对吗?因此,'b 本身并没有被使用,它是调用者(传递地)必须遵守的要求的表达。
-
您的问题已经说明了它适用于哪个版本:我正在为引用类型实现一个特征使用 Rust 1.30。