1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-03-21 14:46:37 +02:00

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.
This commit is contained in:
Dustin J. Mitchell 2025-01-23 03:35:11 -05:00 committed by GitHub
parent 9f9f845acc
commit 15e46379b1
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -8,19 +8,24 @@ If a data type stores borrowed data, it must be annotated with a lifetime:
```rust,editable ```rust,editable
#[derive(Debug)] #[derive(Debug)]
struct Highlight<'doc>(&'doc str); enum HighlightColor {
Pink,
Yellow,
}
fn erase(text: String) { #[derive(Debug)]
println!("Bye {text}!"); struct Highlight<'text> {
slice: &'text str,
color: HighlightColor,
} }
fn main() { fn main() {
let text = String::from("The quick brown fox jumps over the lazy dog."); let text = String::from("The quick brown fox jumps over the lazy dog.");
let fox = Highlight(&text[4..19]); let noun = Highlight { slice: &text[16..19], color: HighlightColor::Yellow };
let dog = Highlight(&text[35..43]); let verb = Highlight { slice: &text[20..25], color: HighlightColor::Pink };
// erase(text); // drop(text);
println!("{fox:?}"); println!("{noun:?}");
println!("{dog:?}"); println!("{verb:?}");
} }
``` ```
@ -28,8 +33,9 @@ fn main() {
- In the above example, the annotation on `Highlight` enforces that the data - 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 underlying the contained `&str` lives at least as long as any instance of
`Highlight` that uses that data. `Highlight` that uses that data. A struct cannot live longer than the data it
- If `text` is consumed before the end of the lifetime of `fox` (or `dog`), the references.
- If `text` is dropped before the end of the lifetime of `noun` or `verb`, the
borrow checker throws an error. borrow checker throws an error.
- Types with borrowed data force users to hold on to the original data. This can - 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 be useful for creating lightweight views, but it generally makes them somewhat