Structs Hold Borrowed Fields With Lifetimes
Let structs borrow their fields instead of owning them, propagating the input lifetime through constructors so views stay zero-copy.
Code
struct Stats<'a> {
label: &'a str,
values: &'a [i32],
}
impl<'a> Stats<'a> {
fn total(&self) -> i32 {
self.values.iter().sum()
}
}
// 返回值借用输入数据的生命周期:不复制即可返回视图
fn summarize<'a>(label: &'a str, values: &'a [i32]) -> Stats<'a> {
Stats { label, values }
}
fn main() {
let raw = vec![3, 9, 4];
let label = String::from("batch-a");
let stats = summarize(&label, &raw);
println!("{} total {}", stats.label, stats.total());
// struct 只持有借用:原始数据始终归所有者管理
println!("owner untouched: {raw:?} {label}");
}Inside the snippet
Structs Hold Borrowed Fields With Lifetimes keeps everything in the functions total, summarize and main.
Putting it to use
The primary signature is fn total(&self) -> i32
The demo output is labeled (owner untouched:), so every printed line maps back to its originating operation.
There are 2 calls inside main — summarize and total — executed top to bottom.
Core lines
self.values.iter().sum()
}
fn summarize<'a>(label: &'a str, values: &'a [i32]) -> Stats<'a> {
Stats { label, values }
}
Interactive Tools for This Topic
FAQ
- What does Structs Hold Borrowed Fields With Lifetimes print when run?
- Run it as a complete program — the output lines carry labels such as `owner untouched:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.