Lifetimes and References
Struct Reference
Holding a Borrowed Field
A struct can hold a reference when its lifetime parameter says the reference stays valid long enough.
Program
Play the program to borrow a label and repeat the borrowed text.
struct_reference.rs
Replay: real traced execution (multi-file project)
struct Label<'a> {
text: &'a str,
}
fn main() {
let word = "trace";
let repeat = 2;
let label = Label { text: word };
let output = label.text.repeat(repeat);
println!("{output}");
}
struct Label<'a> {
text: &'a str,
}
fn main() {
let word = "trace";
let repeat = 3;
let label = Label { text: word };
let output = label.text.repeat(repeat);
println!("{output}");
}
struct Label<'a> {
text: &'a str,
}
fn main() {
let word = "trace";
let repeat = 4;
let label = Label { text: word };
let output = label.text.repeat(repeat);
println!("{output}");
}
word ← "trace", repeat ← 2, label ← (empty), output ← "tracetrace"
5fn main() {6 let wor→ "trace"d = "trace";7 let repea→ 2t = 2; //@repeat=3, 48 let labe→ (empty)l = Label { text: wor"trace"d };9 let outpu→ "tracetrace"t = label.text.repeat(repeat);10 println!("{output}");11}outputtracetrace
word ← "trace", repeat ← 3, label ← (empty), output ← "tracetracetrace"
5fn main() {6 let wor→ "trace"d = "trace";7 let repea→ 3t = 3;8 let labe→ (empty)l = Label { text: wor"trace"d };9 let outpu→ "tracetracetrace"t = label.text.repeat(repeat);10 println!("{output}");11}outputtracetracetrace
word ← "trace", repeat ← 4, label ← (empty), output ← "tracetracetracetrace"
5fn main() {6 let wor→ "trace"d = "trace";7 let repea→ 4t = 4;8 let labe→ (empty)l = Label { text: wor"trace"d };9 let outpu→ "tracetracetracetrace"t = label.text.repeat(repeat);10 println!("{output}");11}outputtracetracetracetrace
lifetime on struct
`Label<'a>` says the struct contains a reference valid for `'a`.
borrowed field
`text: &'a str` stores a borrowed string slice.
method on borrow
`label.text.repeat(repeat)` reads through the borrowed field.