Rust — Lifetimes
Lifetime annotations
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() { x } else { y }
}
fn main() {
let result;
let s1 = String::from("long string");
{
let s2 = String::from("xyz");
result = longest(&s1, &s2);
}
// Error: s2 doesn't live long enough
}
Struct lifetimes
struct ImportantExcerpt<'a> {
part: &'a str,
}
fn main() {
let novel = String::from("Call me Ishmael. Some years ago...");
let first_sentence = novel.split('.').next().unwrap();
let excerpt = ImportantExcerpt {
part: first_sentence,
};
println!("{}", excerpt.part);
}
Lifetime elision
// These are equivalent:
fn first_word(s: &str) -> &str { &s[..1] }
fn first_word<'a>(s: &'a str) -> &'a str { &s[..1] }
Static lifetime
fn main() {
let s: &'static str = "I live forever";
println!("{}", s);
}
Generic type parameters, trait bounds, and lifetimes
use std::fmt::Display;
fn longest_with_announcement<'a, T>(
x: &'a str,
y: &'a str,
ann: T,
) -> &'a str
where
T: Display,
{
println!("Announcement: {}", ann);
if x.len() > y.len() { x } else { y }
}
Mini Practice
Write Rust code that:
- Uses lifetime annotations in a function
- Creates a struct with lifetime parameters
- Demonstrates lifetime elision
- Uses
'staticlifetime
Up Next
In the next lesson, you'll learn about Error Handling — Result and Option.
Related Topics
Frequently Asked Questions about Lifetimes
What is Lifetimes in Rust?
Lifetimes is a fundamental concept in Rust. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Lifetimes?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Lifetimes.
Why is Lifetimes important in Rust?
Lifetimes is essential for Rust development. Understanding this concept will help you write better code and solve real-world problems more effectively.