rust / beginner
Snippet
Basic Lifetime Annotations
Lifetimes ensure references stay valid as long as needed. The 'a annotation says both inputs and the output share the same lifetime. The compiler uses this to prevent dangling references.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {if x.len() > y.len() {x} else {y}}fn main() {let s1 = String::from("long string");let result;{let s2 = String::from("xyz");result = longest(s1.as_str(), s2.as_str());println!("Longest: {}", result);}}
Breakdown
1
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str
'a declares a lifetime parameter; both inputs outlive 'a
2
if x.len() > y.len() { x } else { y }
Returns a reference that must not outlive 'a
3
result = longest(s1.as_str(), s2.as_str());
Pass borrowed string slices, not owned values
4
println! runs before s2 drops at end of block
result is used while both borrowed references are still valid