我正在使用一个早于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

最初的例子

(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 {

I declare the lifetime on the impl (now it compiles)

(Rust playground link)

// was: impl Add for &'b Inches {
impl<'b> Add for &'b Inches {
    ...
}

最后,它可以正确编译.

我的问题

为什么impl Add for &Inches人中有&Inches人被认为缺乏

推荐答案

Rust 1.31 and above

原因很简单:直到Rust 1.31才实现.

现在,初始示例已编译,您可以编写impl Add for &Inches而不是impl<'b> Add for &'b Inches.这是因为1.31.0 stabilized new lifetime elision rules.

Before Rust 1.31

如果你看一下RFC for lifetime elision,你会发现你的用例应该包括:

impl Reader for BufReader { ... }                       // elided
impl<'a> Reader for BufReader<'a> { .. }                // expanded

然而,我在操场上试了it doesn't work次.原因是it's not implemented yet.

我为这种情况查阅了Rust的源代码,但令人惊讶的是,它们很少.我只能在本机类型上找到这一系列Add美元的实现:

impl Add<u8> for u8
impl<'a> Add<u8> for &'a u8
impl<'a> Add<&'a u8> for u8
impl<'a, 'b> Add<&'a u8> for &'b u8

正如你所看到的,生命周期在这里都是明确的;没有回避.

对于您的具体问题,我相信在RFC实现完成之前,您必须坚持使用显式生命周期!

Rust相关问答推荐

如何处理对打包字段的引用是未对齐错误?

如何在Rust中在屏幕中间打印内容?

为什么要在WASM库中查看Rust函数需要`#[no_mangle]`?

有没有更好的方法从HashMap的条目初始化 struct ?

这个规则关于或模式到底是什么意思?如果表达片段的类型与p_i|q_i...&q;不一致,就会形成

RUST应用程序正在退出,错误代码为:(退出代码:0xc0000005,STATUS_ACCESS_VIOLATION)

从未排序的链表中删除重复项的铁 rust 代码在ELSE分支的低级上做了什么?

如何使用Actix Web for Rust高效地为大文件服务

如何轮询 Pin>?

为什么我需要 to_string 函数的参考?

借来的价值生命周期 不够长,不确定为什么它仍然是借来的

Rust LinkedList 中的borrow 判断器错误的原因是什么?

Rust 并行获取对 ndarray 的每个元素的可变引用

在描述棋盘时如何最好地使用特征与枚举

Button.set_hexpand(false) 不会阻止按钮展开

一旦令牌作为文字使用,声明宏不匹配硬编码值?

从嵌入式 Rust 中的某个时刻开始经过的时间

Rust/Serde/HTTP:序列化`Option`

如何在 Rust 中将 UTF-8 十六进制值转换为 char?

为什么我可以从读取的可变自引用中移出?