5. You want to create a counter that increases by 1 each time a function is called. Which of these Rust code snippets correctly uses an immutable variable to achieve this behavior?
hard
A. Use let mut count = 0; and increment inside the function.
B. Use let count = 0; and reassign count = count + 1; inside the function.
C. Use let count = 0; and return count + 1 without changing count.
D. Use let mut count = 0; but never increment it.
Solution
Step 1: Understand immutability and counter logic
An immutable variable cannot be changed, so you cannot increment it directly.
Step 2: Analyze options for correct usage
Use let count = 0; and return count + 1 without changing count. uses an immutable variable count and returns count + 1 without changing count, which respects immutability and simulates increment.
Final Answer:
Use let count = 0; and return count + 1 without changing count. -> Option C
Quick Check:
Immutable means no change; return new value instead = A [OK]
Hint: Immutable vars can't change; return new value instead [OK]
Common Mistakes:
Trying to reassign immutable variable
Forgetting to declare variable mutable when needed
Ignoring that immutable variables can't be incremented
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.