我正在使用一个早于1.31的Rust实现一个引用类型的特性.Why does Rust want an explicit lifetime when I tell it what reference type I'm implementing the trait for?
下面是一个简单的例子.struct 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 {
I declare the lifetime on the impl
(now it compiles)
// was: impl Add for &'b Inches {
impl<'b> Add for &'b Inches {
...
}
最后,它可以正确编译.
我的问题
为什么
impl Add for &Inches
人中有&Inches
人被认为缺乏