Concept Flow - Why lifetimes exist
Start: Reference created
Check: Reference valid?
Use reference
End
This flow shows how Rust checks if a reference is valid during compilation using lifetimes to prevent errors.
fn main() {
let r;
{
let x = 5;
r = &x;
}
println!("{}", r);
}| Step | Action | Variable States | Lifetime Check | Result |
|---|---|---|---|---|
| 1 | Declare r (reference) | r: uninitialized | N/A | OK |
| 2 | Enter inner scope | x: uninitialized | N/A | OK |
| 3 | Initialize x = 5 | x: 5 | N/A | OK |
| 4 | Assign r = &x | r: &x (points to 5) | r lifetime <= x lifetime? | OK |
| 5 | Exit inner scope | x: dropped | r now dangling? | Error: r points to invalid memory |
| 6 | Attempt println!("{}", r) | r: dangling reference | Compile error | Program does not compile |
| Variable | Start | After Step 3 | After Step 4 | After Step 5 | Final |
|---|---|---|---|---|---|
| x | uninitialized | 5 | 5 | dropped | dropped |
| r | uninitialized | uninitialized | &x (valid) | &x (dangling) | dangling |
Rust lifetimes track how long references are valid. They prevent dangling references by ensuring references don't outlive data. Compiler checks lifetimes at compile time. If a reference lives longer than the data it points to, compilation fails. Lifetimes help keep programs safe and bug-free.
Why does Rust use lifetimes like 'a in its code?
Which of the following is the correct way to declare a function with a lifetime parameter 'a for a reference argument in Rust?
fn example(____ s: &'a str) -> &'a str { s }'a and used on references.'a and uses it on both input and output references.What will this Rust code print?
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() > y.len() { x } else { y }
}
fn main() {
let s1 = String::from("apple");
let s2 = "banana";
let result = longest(&s1, s2);
println!("{}", result);
}Identify the error in this Rust code related to lifetimes:
fn first_word(s: &str) -> &str {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &s[0..i];
}
}
&s
}
fn main() {
let word;
{
let s = String::from("hello world");
word = first_word(&s);
}
println!("{}", word);
}You want to write a function that returns a reference to the longer string slice between two inputs, but one input is owned String and the other is a string slice &str. How should you use lifetimes to make this safe and correct?
Pass the test and this pattern moves unknown