Challenge - 5 Problems
Rust Borrowing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateWhat is the output of this Rust code involving borrowing?
Consider the following Rust code. What will it print when run?
Rust
fn main() {
let s = String::from("hello");
let len = calculate_length(&s);
println!("The length of '{}' is {}.", s, len);
}
fn calculate_length(s: &String) -> usize {
s.len()
}Attempts:
2 left
💡 Hint
Look at how the function borrows the string without taking ownership.
✗ Incorrect
The function `calculate_length` borrows `s` immutably using `&s`. This means ownership is not moved, so `s` can still be used after the function call. The length of 'hello' is 5, so the output prints correctly.
❓ Predict Output
intermediateWhat error does this Rust code produce without borrowing?
What error will this Rust code produce when compiled?
Rust
fn main() {
let s = String::from("hello");
let len = calculate_length(s);
println!("The length of '{}' is {}.", s, len);
}
fn calculate_length(s: String) -> usize {
s.len()
}Attempts:
2 left
💡 Hint
Passing `s` by value moves ownership, so `s` cannot be used after.
✗ Incorrect
The function `calculate_length` takes ownership of `s`. After the call, `s` is moved and cannot be used in `println!`. This causes a compile-time error about use of moved value.
🔧 Debug
advancedWhy does this Rust code fail to compile?
Identify the reason this Rust code does not compile.
Rust
fn main() {
let mut s = String::from("hello");
let r1 = &s;
let r2 = &mut s;
println!("{} and {}", r1, r2);
}Attempts:
2 left
💡 Hint
Rust enforces only one mutable reference or multiple immutable references at a time.
✗ Incorrect
The code tries to create an immutable reference `r1` and a mutable reference `r2` to `s` at the same time. Rust forbids this to prevent data races, so it causes a compile error.
🧠 Conceptual
advancedWhy is borrowing important in Rust?
Which of the following best explains why borrowing is required in Rust?
Attempts:
2 left
💡 Hint
Think about how Rust prevents bugs related to memory safety.
✗ Incorrect
Borrowing lets Rust let multiple parts of code read or write data safely without transferring ownership. This prevents bugs like data races and dangling pointers without needing a garbage collector.
❓ Predict Output
expertWhat is the output of this Rust code demonstrating borrowing rules?
Analyze the code and select the correct output or error message.
Rust
fn main() {
let mut s = String::from("hello");
let r1 = &s;
let r2 = &s;
println!("{} and {}", r1, r2);
let r3 = &mut s;
r3.push_str(", world");
println!("{}", r3);
}Attempts:
2 left
💡 Hint
Rust does not allow mutable borrow while immutable borrows are active.
✗ Incorrect
The code tries to create two immutable references `r1` and `r2` and then a mutable reference `r3` before the immutable references go out of scope. Rust forbids this and produces a compile error.
