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
struct Label<'a> {
text: &'a str,
}
fn main() {
let word = "trace";
let repeat = ;
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 = ;
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 = ;
let label = Label { text: word };
let output = label.text.repeat(repeat);
println!("{output}");
}
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.