src/lifetimes/struct-lifetimes.md
If a data type stores borrowed data, it must be annotated with a lifetime:
# // Copyright 2024 Google LLC
# // SPDX-License-Identifier: Apache-2.0
#
#[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);
}
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.doc is dropped before the end of the lifetime of noun or verb, the
borrow checker throws an error.