Challenge - 5 Problems
Rust Ownership Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateUnderstanding ownership transfer in Rust
What is the output of this Rust program?
Rust
fn main() {
let s1 = String::from("hello");
let s2 = s1;
println!("{}", s2);
}Attempts:
2 left
💡 Hint
Remember that in Rust, assigning a String moves ownership, so s1 is no longer valid after the move.
✗ Incorrect
The ownership of the String is moved from s1 to s2. Printing s2 works fine. Using s1 after move would cause a compile error, but here s1 is not used after move.
❓ Predict Output
intermediateBorrowing and scope lifetime
What will this Rust code print?
Rust
fn main() {
let s = String::from("world");
{
let r = &s;
println!("{}", r);
}
println!("{}", s);
}Attempts:
2 left
💡 Hint
The reference r is valid only inside the inner block, but s is still valid after.
✗ Incorrect
The reference r borrows s inside the inner block and is printed. After the block ends, r is dropped, so s can be used again safely.
❓ Predict Output
advancedMutable borrow and scope rules
What error or output does this Rust code produce?
Rust
fn main() {
let mut s = String::from("hello");
let r1 = &mut s;
let r2 = &mut s;
println!("{} and {}", r1, r2);
}Attempts:
2 left
💡 Hint
Rust allows only one mutable reference at a time to prevent data races.
✗ Incorrect
The code tries to create two mutable references to s simultaneously, which Rust forbids and causes a compile-time error.
❓ Predict Output
advancedDangling reference prevention
What happens when you run this Rust code?
Rust
fn dangle() -> &String { let s = String::from("hello"); &s } fn main() { let reference = dangle(); println!("{}", reference); }
Attempts:
2 left
💡 Hint
Rust prevents returning references to data that will be dropped.
✗ Incorrect
The function returns a reference to a local variable that is dropped when the function ends, which Rust forbids at compile time.
🧠 Conceptual
expertOwnership and borrowing combined scenario
Consider this Rust code snippet. What is the value of 'count' after execution?
Rust
fn main() {
let mut count = 0;
let mut s = String::from("hello");
{
let r1 = &s;
let r2 = &s;
count += r1.len() + r2.len();
}
let r3 = &mut s;
r3.push_str(" world");
count += r3.len();
println!("{}", count);
}Attempts:
2 left
💡 Hint
Immutable borrows end before mutable borrow starts, so all operations are valid.
✗ Incorrect
r1 and r2 borrow s immutably inside the inner block, their scope ends before r3 mutable borrow. The lengths add up to 21 (5+5+11).
