理解这个 Rust 生命周期示例

Understanding of this Rust lifetime example

我是 Rust 的新手,我仍在为 Rust 的 lifetimes 苦苦挣扎。下面是我正在阅读的一本书中的一个例子。谁能帮忙解释一下为什么作者只看函数签名就能得到这些信息?我已经对borrowingreferences等有了基本的了解,但还是看不懂。

For example, suppose we have a parsing function that takes a slice of bytes, and returns a structure holding the results of the parse:

fn parse_record<'i>(input: &'i [u8]) -> Record<'i> { ... }

Without looking into the definition of the Record type at all, we can tell that, if we receive a Record from parse_record, whatever references it contains must point into the input buffer we passed in, and nowhere else (except perhaps at 'static values).

输入:

input: &'i [u8]

表示如下:

我是对一系列字节 ([u8]) 的引用,它们的寿命至少与 'i 一样长。

所以,当我说我有一个看起来像这样的类型时:Record<'i>,我可以这样说:

我是一个结构体(命名为 Record<'i>),其中包含某些东西(可能是引用,可能是其他东西),它依赖于 某物 至少存活了'i

references/structs/enums/whatever 上的生命周期告诉你的是,存在一种依赖关系,即存在于 'i 中的对象必须与我一样存在。

换句话说,此函数签名告诉您 Record 必须与 input 引用的字节一样长(u8s 引用,而不是引用本身)。


最近弃用了缺少生命周期参数,现在会导致警告,因此在阅读以下示例时请记住:

fn parse_record(input: &[u8]) -> Record

可能 终生依附于 Record,因此您必须查阅某种文档。编译将此(并且警告要求您自己执行此操作)脱糖为:

fn parse_record(input: &'_ [u8]) -> Record<'_>

这与您的 'i 示例相同。

Record只能从函数体中获取引用。理论上,这些可以来自

  • input 中的值,这些都是生命周期为 'i
  • 的引用
  • parse_record 之外定义的值,必须具有 'static 生命周期
  • parse_record 中定义的值。这些可以是
    • 动态创建。这些值将在函数范围的末尾被删除,因此对它们的任何引用最终都会成为悬空指针。因此,编译器不允许这样做。
    • 文字(1"cat")。这些实际上被烘焙到二进制文件中,因此在函数外部有效定义。在函数中它们是 'static 引用