Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to move ownership of the String to variable b.
Rust
let a = String::from("hello"); let b = [1];
Attempts:
3 left
💡 Hint
Common Mistakes
Using &a borrows instead of moves ownership.
Using a.clone() creates a copy, not a move.
✗ Incorrect
In Rust, assigning
a to b moves ownership, so b owns the String now.2fill in blank
mediumComplete the code to fix the error by cloning the String before moving.
Rust
let s1 = String::from("hello"); let s2 = [1];
Attempts:
3 left
💡 Hint
Common Mistakes
Using
s1 moves ownership, invalidating s1.Using
&s1 only borrows, not clones.✗ Incorrect
Cloning
s1 creates a new String, so s2 owns a copy and s1 remains valid.3fill in blank
hardFix the error by completing the code to borrow the String instead of moving it.
Rust
fn print_string(s: [1]) { println!("{}", s); } let s = String::from("hello"); print_string(s); print_string(s);
Attempts:
3 left
💡 Hint
Common Mistakes
Using
String moves ownership, so second call fails.Using
str is a string slice type, but not a reference.✗ Incorrect
Borrowing with
&String allows multiple uses without moving ownership.4fill in blank
hardComplete the code to create a vector of Strings by moving ownership inside the loop.
Rust
let words = vec![String::from("apple"), String::from("banana")]; let mut new_words = Vec::new(); for word in words[1] { new_words.push(word); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using
iter() borrows, causing ownership errors.Cloning unnecessarily copies data.
✗ Incorrect
Using
into_iter() moves ownership of each String from words. No need to clone when pushing.5fill in blank
hardFill all three blanks to implement a function that takes ownership of a String, modifies it, and returns it.
Rust
fn add_exclamation[1] { let mut s = [2]; s.push('!'); [3] } let greeting = String::from("Hello"); let excited = add_exclamation(greeting);
Attempts:
3 left
💡 Hint
Common Mistakes
Using a reference in the signature causes ownership issues.
Not returning the String loses ownership.
✗ Incorrect
The function takes ownership of
s, modifies it, and returns it to transfer ownership back.