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

标签 rust lifetime-scoping

如果我有这两个功能

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

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

什么时候 foo 会返回一个错误并且 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 上)。这是一样的一生!所以你在这里对编译器说的是:“这个函数引用了一个包含内部引用的 blah。我将返回与 blah 的内部引用一样长的东西。”在这种情况下,签名会强烈暗示您可能会返回来自 blah 内部的东西。

关于rust - 我什么时候需要在 Rust 中指定明确的生命周期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31083746/

相关文章:

rust - async_std::sync::Arc 的目的是什么?

generics - 使用生命周期参数的结果-将生命周期参数的枚举应用于默认T <'a> and E<' a>参数(Rust)

sqlite - 如何存储 SQLite 准备好的语句供以后使用?

rust - 在 Rust 中左移负值是未定义的行为吗?

generics - 创建新的通用结构的正确方法是什么?

git - "git pull"是如何用 git2-rs Rust crate 完成的?

rust - 从 rust-xcb 调用 "does not live long enough"时出现 `roots` 错误

rust - 什么是非词汇生命周期?

rust - 什么是非词法生命周期?

oop - 为二叉树实现 IntoIterator