Skip to content

Commit

Permalink
Clarify struct-lifetimes slide (#2585)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
djmitche authored Jan 23, 2025
1 parent 9f9f845 commit 15e4637
Showing 1 changed file with 16 additions and 10 deletions.
26 changes: 16 additions & 10 deletions src/lifetimes/struct-lifetimes.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,28 +8,34 @@ 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:?}");
}
```

<details>

- 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
Expand Down

0 comments on commit 15e4637

Please sign in to comment.