Lifetimes help Rust know how long references are valid. This keeps your program safe from using data that no longer exists.
Lifetimes in functions in Rust
fn function_name<'a>(param: &'a Type) -> &'a Type { // function body }
The &'a means a reference with lifetime 'a.
You declare lifetime parameters with <'a> after the function name.
'a ties the output to the input, so Rust knows the returned reference is valid as long as the input is.fn first_word<'a>(s: &'a str) -> &'a str { let bytes = s.as_bytes(); for (i, &item) in bytes.iter().enumerate() { if item == b' ' { return &s[0..i]; } } &s[..] }
'a, so Rust knows the output reference is valid as long as both inputs are.fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { if x.len() > y.len() { x } else { y } }
This program defines a function longest that returns the longer of two string slices. The lifetime 'a ensures the returned reference is valid as long as both inputs are valid. In main, it prints the longer string.
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { if x.len() > y.len() { x } else { y } } fn main() { let string1 = String::from("apple"); let string2 = "banana"; let result = longest(string1.as_str(), string2); println!("The longest string is: {}", result); }
Every reference in Rust has a lifetime, even if you don't write it explicitly.
Using lifetimes helps prevent bugs where you use data after it's gone.
If you don't specify lifetimes when needed, Rust will give an error to keep your code safe.
Lifetimes tell Rust how long references are valid.
Functions with references often need lifetime annotations to connect input and output lifetimes.
This helps Rust prevent bugs with invalid references and keeps your program safe.