capypad
0 day streak
rust / intermediate
Snippet

Lifetimes in Function Signatures

Lifetimes specify how long references are valid in your code. When functions return references, Rust needs to know the relationship between input and output lifetimes. Lifetime annotations create contracts ensuring references won't outlive the data they point to.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() { x } else { y }
}
 
fn first_word(s: &str) -> &str {
match s.find(' ') {
Some(i) => &s[..i],
None => s,
}
}
 
struct ImportantExcerpt<'a> {
part: &'a str,
}
 
impl<'a> ImportantExcerpt<'a> {
fn announce_and_return(&self, announcement: &str) -> &str {
println!("Announcement: {}", announcement);
self.part
}
}
 
fn main() {
let s1 = String::from("long string");
let result;
{
let s2 = String::from("xy");
result = longest(s1.as_str(), s2.as_str());
println!("Longest: {}", result);
}
}
Breakdown
1
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str
Lifetime 'a connects input lifetimes to output lifetime
2
struct ImportantExcerpt<'a>
Struct holds reference, lifetime ties it to struct's lifetime
3
fn announce_and_return(&self, announcement: &str) -> &str
Method lifetime tied to &self, not the parameter
4
result = longest(...)
Result used while s2 is still valid, not after s2 drops