我什么时候需要在 Rust 中指定明确的生命周期?

When do I need to specify explicit lifetimes in Rust?

如果我有这两个功能

// implicit
fn foo(x: &i32) {
}

// explicit
fn bar<'a>(x: &'a i32) {
}

什么时候 foo return 会出错而 bar 是正确的函数头?我很困惑为什么我会明确声明一生:

The 'a reads ‘the lifetime a’. Technically, every reference has some lifetime associated with it, but the compiler lets you elide them in common cases.

我明白什么是生命周期,但是明确指定生命周期 'a 对我有什么用?作为参考,我使用 Rust book 作为阅读 material

实际上,您必须编写生命周期注释的第一个原因是因为编译器要求您这样做。它将拒绝 lifetime elision rules 未涵盖的函数签名。

我假设您想要一个生命周期是强制性的简单示例。想象一下以下场景:

struct Blah<'a> {
    hoy: &'a u8
}

fn want_a_hoy(blah: &Blah) -> &u8 {
    blah.hoy
}

意图很明显,但编译器没有处理:

<anon>:7:35: 7:38 error: missing lifetime specifier [E0106]
<anon>:7     fn want_a_hoy(blah: &Blah) -> &u8 {
                                           ^~~
<anon>:7:35: 7:38 help: see the detailed explanation for E0106
<anon>:7:35: 7:38 help: this function's return type contains a borrowed value, but 
                        the signature does not say which one of `blah`'s 2 elided 
                        lifetimes it is borrowed from

在这种情况下,注释解决了问题:

fn want_a_hoy<'a, 'b>(blah: &'b Blah<'a>) -> &'a u8 {
    blah.hoy
}

此处您指定了 'a 两次(在 Blah<'a>&'a 上)。这是一样的一生!所以你在这里对编译器说的是:"This function takes a reference to a blah containing an inner reference. I will return something which lives exactly as long as the inner reference of the blah." 在这种情况下,签名强烈暗示你可能 return 来自废话内部的东西。