Swiftorial Logo
Home
Swift Lessons
AI Tools
Learn More
Career
Resources

Rust FAQ: Top Questions

5. What are lifetimes in Rust and why are they important?

Rust uses lifetimes to track how long references are valid. They prevent dangling references by enforcing that borrowed data lives long enough.

  • Lifetime annotations tell the compiler how reference scopes relate to each other.
  • Borrow checker uses lifetimes to validate code safety at compile time.
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() > y.len() { x } else { y }
}

Explanation: The function returns a reference valid as long as both inputs are valid. This avoids returning a reference to deallocated memory.