0
0
Rustprogramming~5 mins

Mutable variables in Rust - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does it mean when a variable is mutable in Rust?
A mutable variable in Rust means you can change its value after it is first set. You declare it with mut before the variable name.
Click to reveal answer
beginner
How do you declare a mutable variable named count with the value 5 in Rust?
You write: <code>let mut count = 5;</code> This means <code>count</code> can be changed later.
Click to reveal answer
beginner
What happens if you try to change a variable that is not mutable in Rust?
Rust will give a compile-time error because variables are immutable by default. You must declare them as mutable to change their value.
Click to reveal answer
intermediate
Why does Rust make variables immutable by default?
Immutability helps prevent bugs by avoiding unexpected changes. It makes programs safer and easier to understand.
Click to reveal answer
beginner
Show an example of changing a mutable variable's value in Rust.
Example:<br><code>let mut score = 10;<br>score = 20;<br>println!("Score is {}", score);</code><br>This prints: <code>Score is 20</code>
Click to reveal answer
How do you declare a mutable variable in Rust?
Avar variable_name = value;
Blet mut variable_name = value;
Cmutable variable_name = value;
Dlet variable_name = mut value;
What is the default mutability of variables in Rust?
AMutable
BDepends on the type
CImmutable
DMutable only for integers
What error occurs if you try to change an immutable variable?
ACompile-time error
BWarning only
CNo error, it works fine
DRuntime error
Why is immutability preferred by default in Rust?
ATo prevent unexpected changes and bugs
BTo make code run faster
CBecause mutable variables are not supported
DTo save memory
Which of the following is a correct way to change a mutable variable's value?
Alet x = mut 5; x = 10;
Blet x = 5; x = 10;
Clet mut x = 5; mut x = 10;
Dlet mut x = 5; x = 10;
Explain what mutable variables are in Rust and how to declare them.
Think about how you can change a variable's value after setting it.
You got /3 concepts.
    Describe why Rust makes variables immutable by default and the benefits of this choice.
    Consider how fixing values helps avoid mistakes.
    You got /4 concepts.