Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create an immutable reference to the variable num.
Rust
let num = 10; let r = [1]num; println!("{}", r);
Attempts:
3 left
💡 Hint
Common Mistakes
Using
* which dereferences a pointer instead of creating a reference.Using
mut which is for mutable references.Using
ref which is used in patterns, not for creating references.✗ Incorrect
The ampersand
& creates an immutable reference to the variable.2fill in blank
mediumComplete the code to print the value through an immutable reference r.
Rust
let num = 20; let r = # println!("{}", [1]r);
Attempts:
3 left
💡 Hint
Common Mistakes
Using
& which creates a reference instead of dereferencing.Using
ref which is not used here.Using
mut which is for mutability.✗ Incorrect
The asterisk
* dereferences the immutable reference to access the value.3fill in blank
hardFix the error by completing the code to borrow text immutably.
Rust
let text = String::from("hello"); let r = [1]text; println!("{}", r);
Attempts:
3 left
💡 Hint
Common Mistakes
Using
&mut which tries to borrow mutably.Using
* which dereferences instead of borrowing.Using
ref which is not correct here.✗ Incorrect
Using
& borrows text immutably, fixing the error.4fill in blank
hardFill both blanks to create a dictionary comprehension that maps words to their lengths only if the length is greater than 3.
Rust
let words = vec!["apple", "cat", "banana"]; let lengths = words.iter().filter(|&&word| word.len() [1] 3).map(|&word| (word, word.len())).collect::<std::collections::HashMap<_, _>>();
Attempts:
3 left
💡 Hint
Common Mistakes
Using
< which filters words shorter than 3.Using
== which filters words exactly length 3.Using
!= which filters words not length 3.✗ Incorrect
The operator
> filters words with length greater than 3.5fill in blank
hardFill all three blanks to create a HashMap from words to their lengths, filtering words with length greater than 3.
Rust
let words = vec!["apple", "cat", "banana"]; let lengths = words.iter().filter(|&&word| word.len() [1] 3).map(|&word| ([2], [3])).collect::<std::collections::HashMap<_, _>>();
Attempts:
3 left
💡 Hint
Common Mistakes
Using
< instead of > for filtering.Swapping key and value in the tuple.
Using incorrect variable names.
✗ Incorrect
Use
> to filter, then map each word to a tuple of (word, word.len()).