📖 Scenario: You are writing a simple Rust program that works with string slices. Rust uses lifetimes to make sure references are valid. Lifetime elision rules help Rust guess lifetimes so you don't have to write them all the time.In this project, you will create a function that returns the longer of two string slices. You will see how Rust applies lifetime elision rules to make your code simpler and safe.
🎯 Goal: Build a Rust function called longer_string that takes two string slices and returns the longer one. Use lifetime elision rules so you don't have to write explicit lifetime annotations.
📋 What You'll Learn
Create two string slices with exact values
Write a function longer_string that takes two string slices as parameters
Use lifetime elision rules by NOT writing explicit lifetime annotations
Return the longer string slice from the function
Print the result of calling longer_string with the two slices
💡 Why This Matters
🌍 Real World
Rust programs often use references to avoid copying data. Understanding lifetime elision helps write safe and clean code when working with references.
💼 Career
Many Rust jobs require knowledge of lifetimes to manage memory safely without garbage collection. This project builds foundational skills for writing reliable Rust code.
Progress0 / 4 steps
1
Create two string slices
Create two string slices called string1 with value "hello" and string2 with value "world!".
Rust
Hint
Use let to create string slices with double quotes.
2
Write the longer_string function without explicit lifetimes
Write a function called longer_string that takes two parameters: x and y, both of type &str. Return the longer string slice. Do NOT write explicit lifetime annotations; rely on Rust's lifetime elision rules.
Rust
Hint
Write the function header with parameters x: &str and y: &str. Return type is &str. Use an if statement to compare lengths.
3
Call the function with the two string slices
Create a variable called result and assign it the value returned by calling longer_string with string1 and string2 as arguments.
Rust
Hint
Call longer_string with string1 and string2. Store the return value in result.
4
Print the result
Write a println! macro call to print the value of result.
Rust
Hint
Use println!("{}", result); to print the string slice stored in result.
Practice
(1/5)
1. Which of the following best describes the purpose of Rust's lifetime elision rules?
easy
A. To let Rust automatically fill in lifetimes in common cases without explicit annotations.
B. To force the programmer to always write explicit lifetime annotations.
C. To remove all lifetimes from the code for simplicity.
D. To allow Rust to ignore lifetime errors during compilation.
Solution
Step 1: Understand lifetime elision rules
Lifetime elision rules help Rust guess lifetimes automatically in common cases.
Step 2: Compare options
Only To let Rust automatically fill in lifetimes in common cases without explicit annotations. correctly states that Rust fills in lifetimes automatically without needing explicit annotations in many cases.
Final Answer:
To let Rust automatically fill in lifetimes in common cases without explicit annotations. -> Option A
Hint: Elision means Rust guesses lifetimes for you [OK]
Common Mistakes:
Thinking Rust always requires explicit lifetimes
Believing lifetimes are removed entirely
Assuming Rust ignores lifetime errors
2. Which of the following function signatures correctly uses lifetime elision rules in Rust?
easy
A. fn first_word<'a>(s: &'a str) -> &'a str
B. fn first_word(s: &str) -> &str
C. fn first_word(s: &str) -> &'a str
D. fn first_word<'a>(s: &str) -> &str
Solution
Step 1: Recall lifetime elision rules for functions
When a function has one input lifetime, Rust assumes the output lifetime is the same as the input.
Step 2: Analyze options
fn first_word(s: &str) -> &str uses no explicit lifetimes but is valid due to elision. fn first_word<'a>(s: &'a str) -> &'a str is explicit but correct. fn first_word(s: &str) -> &'a str is invalid because it uses an undefined lifetime in output. fn first_word<'a>(s: &str) -> &str mixes explicit and implicit lifetimes incorrectly.
Final Answer:
fn first_word(s: &str) -> &str -> Option B
Quick Check:
One input ref means output ref gets same lifetime [OK]
Hint: One input ref means output ref lifetime is same [OK]
Common Mistakes:
Using undefined lifetime parameters
Mixing explicit and implicit lifetimes incorrectly
Forgetting elision rules allow omission
3. What will be the output of the following Rust code snippet?
fn longest(x: &str, y: &str) -> &str {
x
}
fn main() {
let string1 = String::from("apple");
let string2 = String::from("banana");
let result = longest(&string1, &string2);
println!("Longest string is: {}", result);
}
medium
A. Runtime error due to dangling reference
B. Longest string is: banana
C. Longest string is: apple
D. Compilation error due to missing lifetime annotations
Solution
Step 1: Check lifetime elision rules for the function
The function takes two input references (x and y) and returns a reference. Elision rules do not apply when there are multiple input lifetimes and an output lifetime; Rust cannot determine which input lifetime to use for the output.
Step 2: Confirm compilation behavior
This results in a compilation error: `missing lifetime specifier`. The code does not compile.
Final Answer:
Compilation error due to missing lifetime annotations -> Option D
Quick Check:
Multiple input refs need explicit lifetimes [OK]
Hint: Two input refs to output requires explicit lifetimes [OK]
Common Mistakes:
Thinking elision allows compilation with multiple input refs
Believing it returns the longer string
Confusing runtime errors with lifetime errors
4. Identify the error in the following Rust function related to lifetime elision rules:
fn invalid_ref(x: &str, y: &str) -> &str {
let result = String::from("hello");
&result
}
medium
A. The function returns a reference to a local variable that will be dropped.
B. The function is missing lifetime annotations on parameters.
C. The function should return a String, not a reference.
D. The function should use explicit lifetime annotations to compile.
Solution
Step 1: Analyze the returned reference
The function returns a reference to 'result', a local String created inside the function.
Step 2: Understand lifetime rules and error
'result' is dropped when the function ends, so returning a reference to it causes a dangling reference error.
Final Answer:
The function returns a reference to a local variable that will be dropped. -> Option A
Quick Check:
Returning local reference causes dangling pointer [OK]
Hint: Never return reference to local variable [OK]
Common Mistakes:
Thinking missing lifetime annotations cause this error