From 15e46379b12e78ccb231053722f2589bd37aeb5a Mon Sep 17 00:00:00 2001 From: "Dustin J. Mitchell" Date: Thu, 23 Jan 2025 03:35:11 -0500 Subject: [PATCH] Clarify struct-lifetimes slide (#2585) In teaching the course, the verbal distinction between "doc" and "dog" was not clear, so this PR moves away from those symbols. This also makes the Highlight struct a little more substantial, and replaces `erase` with a simple call to `drop` to keep the example short. --- src/lifetimes/struct-lifetimes.md | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/src/lifetimes/struct-lifetimes.md b/src/lifetimes/struct-lifetimes.md index f201ba5a..02c4dc55 100644 --- a/src/lifetimes/struct-lifetimes.md +++ b/src/lifetimes/struct-lifetimes.md @@ -8,19 +8,24 @@ If a data type stores borrowed data, it must be annotated with a lifetime: ```rust,editable #[derive(Debug)] -struct Highlight<'doc>(&'doc str); +enum HighlightColor { + Pink, + Yellow, +} -fn erase(text: String) { - println!("Bye {text}!"); +#[derive(Debug)] +struct Highlight<'text> { + slice: &'text str, + color: HighlightColor, } fn main() { let text = String::from("The quick brown fox jumps over the lazy dog."); - let fox = Highlight(&text[4..19]); - let dog = Highlight(&text[35..43]); - // erase(text); - println!("{fox:?}"); - println!("{dog:?}"); + let noun = Highlight { slice: &text[16..19], color: HighlightColor::Yellow }; + let verb = Highlight { slice: &text[20..25], color: HighlightColor::Pink }; + // drop(text); + println!("{noun:?}"); + println!("{verb:?}"); } ``` @@ -28,8 +33,9 @@ fn main() { - 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. -- If `text` is consumed before the end of the lifetime of `fox` (or `dog`), the + `Highlight` that uses that data. A struct cannot live longer than the data it + references. +- If `text` is dropped before the end of the lifetime of `noun` or `verb`, the borrow checker throws an error. - Types with borrowed data force users to hold on to the original data. This can be useful for creating lightweight views, but it generally makes them somewhat