Hint: Use chars().nth(index).unwrap() for safe char access [OK]
Common Mistakes:
Using direct indexing like s[2]
Using get(2) which returns Option<&str> slice, not char
Using bytes() which returns u8, not char
3. What is the output of this Rust code?
let s = "rust"; let mut result = String::new(); for c in s.chars() { if c == 'u' { result.push('U'); } else { result.push(c); } } println!("{}", result);
medium
A. rust
B. rUSt
C. rUst
D. Rust
Solution
Step 1: Iterate over each character in "rust"
The loop goes over 'r', 'u', 's', 't' one by one.
Step 2: Replace 'u' with 'U' and keep others same
When character is 'u', push 'U' to result; else push original char.
Final Answer:
rUst -> Option C
Quick Check:
Only 'u' replaced by 'U' = rUst [OK]
Hint: Check character equality and push accordingly [OK]
Common Mistakes:
Replacing wrong characters
Not pushing characters correctly
Confusing uppercase and lowercase
4. Identify the error in this Rust code snippet:
let s = "hello"; let c = s[1]; println!("{}", c);
medium
A. s is not declared mutable
B. Cannot index string with integer directly
C. Missing semicolon after println!
D. println! macro syntax error
Solution
Step 1: Check string indexing rules in Rust
Rust strings are UTF-8 encoded and do not support direct indexing by integer like arrays.
Step 2: Identify the invalid line
The line let c = s[1]; causes a compile-time error because of invalid indexing.
Final Answer:
Cannot index string with integer directly -> Option B
Quick Check:
Direct indexing on String = error [OK]
Hint: Rust strings can't be indexed by integer directly [OK]
Common Mistakes:
Assuming s[1] works like array indexing
Ignoring UTF-8 encoding complexity
Thinking semicolon or macro syntax is the error
5. Given a string s, how can you create a new string containing only the vowels from s in Rust? Choose the correct code snippet.
hard
A. let vowels: String = s.chars().filter(|c| "aeiou".contains(*c)).collect();
B. let vowels: String = s.bytes().filter(|b| b == b'a' || b == b'e').collect();
C. let vowels: String = s.get(0..5).unwrap().to_string();
D. let vowels: String = s.chars().map(|c| if "aeiou".contains(c) { c } else { ' ' }).collect();
Solution
Step 1: Use chars() to iterate characters
We need to check each character, so chars() is appropriate.
Step 2: Filter vowels and collect into String
Filter characters that are vowels using filter and collect them into a new String.
Final Answer:
let vowels: String = s.chars().filter(|c| "aeiou".contains(*c)).collect(); -> Option A