Consider the following Rust code that uses references with explicit lifetimes. What will it print?
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { if x.len() > y.len() { x } else { y } } fn main() { let string1 = String::from("apple"); let string2 = "banana"; let result = longest(string1.as_str(), string2); println!("{}", result); }
Think about which string slice is longer and how lifetimes ensure safety.
The function longest returns the longer string slice. "banana" is longer than "apple", so it prints "banana".
Look at this Rust code snippet. What error will the compiler show?
fn main() {
let r;
{
let x = 5;
r = &x;
}
println!("{}", r);
}Check the scope of x and the reference r.
The variable x is dropped at the end of the inner block, but r tries to reference it outside that scope. Rust prevents this with a compile-time error.
Identify the reason this Rust code does not compile and what lifetime rule it violates.
fn get_str<'a>() -> &'a str { let s = String::from("hello"); &s } fn main() { let result = get_str(); println!("{}", result); }
Think about the lifetime of s inside the function.
The function returns a reference to s, which is dropped when the function ends. This causes a dangling reference, which Rust forbids.
Choose the correct Rust function signature that returns the longer of two string slices with proper lifetime annotations.
Remember to declare lifetime parameters before using them in references.
Option B correctly declares a single lifetime parameter 'a and uses it consistently for both parameters and the return type.
Given this Rust code using references with lifetimes, how many items will be stored in the vector vec after execution?
fn main() {
let mut vec = Vec::new();
{
let s = String::from("hello");
vec.push(&s);
}
println!("{}", vec.len());
}Consider the lifetime of s and the reference stored in the vector.
The reference to s is pushed into the vector, but s is dropped at the end of the inner block. Rust prevents storing a reference that may become invalid, causing a compile-time error.