Challenge - 5 Problems
Rust Move 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 move semantics?
Consider the following Rust code. What will it print when run?
Rust
fn main() {
let s1 = String::from("hello");
let s2 = s1;
// println!("{}", s1); // Uncommenting this line causes error
println!("{}", s2);
}Attempts:
2 left
💡 Hint
Remember that assigning s1 to s2 moves ownership, so s1 cannot be used after.
✗ Incorrect
The ownership of the String is moved from s1 to s2. Using s1 after move causes compile error, but here s2 is printed, so output is 'hello'.
❓ Predict Output
intermediateWhat happens when you try to use a moved value in Rust?
What error will this Rust code produce?
Rust
fn main() {
let v1 = vec![1, 2, 3];
let v2 = v1;
println!("{}", v1.len());
}Attempts:
2 left
💡 Hint
After moving v1 to v2, v1 cannot be used anymore.
✗ Incorrect
The vector v1 is moved to v2. Using v1 after move causes a compile-time error.
🔧 Debug
advancedIdentify the cause of the error in this Rust code using move semantics
Why does this Rust code fail to compile?
Rust
fn main() {
let s = String::from("hello");
takes_ownership(s);
println!("{}", s);
}
fn takes_ownership(some_string: String) {
println!("{}", some_string);
}Attempts:
2 left
💡 Hint
Think about what happens to ownership when passing s to a function.
✗ Incorrect
The function takes ownership of s, so s is invalid after the call. Using s after move causes compile error.
❓ Predict Output
advancedWhat is the output of this Rust code with cloning and move?
What will this Rust program print?
Rust
fn main() {
let s1 = String::from("hello");
let s2 = s1.clone();
println!("{} {}", s1, s2);
}Attempts:
2 left
💡 Hint
Cloning creates a deep copy, so both s1 and s2 are valid.
✗ Incorrect
Cloning s1 creates a new String s2 with the same content. Both can be used independently.
❓ Predict Output
expertWhat is the output of this Rust code involving move and borrowing?
Analyze the code and select the correct output.
Rust
fn main() {
let s = String::from("hello");
let r1 = &s;
let r2 = &s;
println!("{} and {}", r1, r2);
let r3 = &mut s;
println!("{}", r3);
}Attempts:
2 left
💡 Hint
Rust does not allow mutable and immutable borrows at the same time.
✗ Incorrect
The code tries to borrow s mutably while immutable borrows are still active, causing a compile error.
