Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a reference to the variable num.
Rust
let num = 10; let num_ref = [1]num; println!("{}", num_ref);
Attempts:
3 left
💡 Hint
Common Mistakes
Using * instead of & to create a reference.
Using ref keyword incorrectly outside of pattern matching.
✗ Incorrect
In Rust, the ampersand
& is used to create a reference to a value without taking ownership.2fill in blank
mediumComplete the code to dereference the reference num_ref and print the value.
Rust
let num = 20; let num_ref = # println!("{}", [1]num_ref);
Attempts:
3 left
💡 Hint
Common Mistakes
Using & instead of * to dereference.
Trying to use ref keyword here.
✗ Incorrect
The asterisk
* is used to dereference a reference and access the value it points to.3fill in blank
hardFix the error in the code by completing the blank to borrow text as a mutable reference.
Rust
let mut text = String::from("hello"); let text_ref = [1]text; text_ref.push_str(", world!"); println!("{}", text_ref);
Attempts:
3 left
💡 Hint
Common Mistakes
Using & instead of &mut when trying to mutate.
Using * which dereferences but does not create a mutable borrow.
✗ Incorrect
To modify the value through a reference, you must borrow it as a mutable reference using
&mut.4fill in blank
hardFill both blanks to create an immutable reference and then dereference it to get the value.
Rust
let value = 42; let ref_value = [1]value; let original = [2]ref_value; println!("{}", original);
Attempts:
3 left
💡 Hint
Common Mistakes
Using &mut instead of & for immutable reference.
Not dereferencing the reference before printing.
✗ Incorrect
First, create an immutable reference with
&. Then dereference it with * to get the original value.5fill in blank
hardFill all three blanks to create a mutable reference, modify the value, and then print the updated value.
Rust
let mut count = 5; let count_ref = [1]count; *[2] = 10; println!("{}", [3]);
Attempts:
3 left
💡 Hint
Common Mistakes
Using & instead of &mut for mutable borrow.
Trying to print the reference instead of the original variable.
✗ Incorrect
Create a mutable reference with
&mut. Dereference it to assign a new value. Then print the original variable which now holds the updated value.