我正在为引用类型实现一个特征 . Why does Rust want an explicit lifetime when I tell it what reference type I'm implementing the trait for?
这是一个简单的例子 . struct Inches
, &Inches
的 Add
trait的实现,以及使用该实现的函数 .
初始示例(不编译)
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 {
...
}
最后,这正确编译 .
我的问题
为什么&inches in impl Add for&Inches被认为缺乏生命周期说明符?通过告诉编译器这个Add方法是针对&Inches的一些未指定的非静态生命周期'b,然后在其他地方从不引用该生命周期,解决了什么问题?
1 回答
如果您查看RFC for lifetime elision,您可以看到您的用例应该包括在内:
但是,我试过围栏和it doesn't work . The reason is plain simple: it's not implemented yet.
我为这些案例编写了Rust的源代码,但令人惊讶的是它们很少 . 我只能在本机类型上找到
Add
的这一系列实现:正如你所看到的,这里的生命周期都是明确的;不会出现任何缺陷 .
对于您的具体问题,我相信您必须坚持使用显式生命周期,直到RFC实现完成!