Tsallaka zuwa abun ciki
Justice Tech School

Lifetimes

Lifetimes tell the compiler how long references are valid. Annotate with 'a when a function returns a reference that depends on its inputs. Most of the time they are inferred.

Example
fn longest<'a>(a: &'a str, b: &'a str) -> &'a str {
    if a.len() >= b.len() { a } else { b }
}
fn main() {
    println!("{}", longest("hello", "hi"));
}

Result

hello

Exercise

Lifetime marker.

fn f<a>() {}

Quiz Test

What do lifetimes prevent?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.