数据结构中的生命周期

如果数据类型存储了借用的数据,则必须对其添加生命周期注释:

#[derive(Debug)]
enum HighlightColor {
    Pink,
    Yellow,
}

#[derive(Debug)]
struct Highlight<'document> {
    slice: &'document str,
    color: HighlightColor,
}

fn main() {
    let doc = String::from("The quick brown fox jumps over the lazy dog.");
    let noun = Highlight { slice: &doc[16..19], color: HighlightColor::Yellow };
    let verb = Highlight { slice: &doc[20..25], color: HighlightColor::Pink };
    // drop(doc);
    dbg!(noun);
    dbg!(verb);
}
This slide should take about 5 minutes.
  • In the above example, the annotation on Highlight enforces that the data underlying the contained &str lives at least as long as any instance of Highlight that uses that data. A struct cannot live longer than the data it references.
  • If doc is dropped before the end of the lifetime of noun or verb, the borrow checker throws an error.
  • 借用数据的类型会迫使用户保留原始数据。这对于创建轻量级视图很有用,但通常会使它们更难使用。
  • 如有可能,让数据结构直接拥有自己的数据。
  • 一些包含多个引用的结构可以有多个生命周期注释。除了结构体本身的生命周期之外,如果需要描述引用之间的生命周期关系,则可能需要这样做。这些都是非常高级的用例。