Introduction
Immutable variables hold values that cannot change once set. This helps keep your program safe and predictable.
Immutable variables hold values that cannot change once set. This helps keep your program safe and predictable.
let variable_name = value;
By default, variables in Rust are immutable.
To make a variable mutable, you add mut after let.
x with value 5.let x = 5; // x cannot be changed later
let name = "Alice"; // name is a string that cannot be changed
mut.let mut y = 10; y = 15; // allowed because y is mutable
This program creates an immutable variable greeting and prints it. Trying to change it later would cause an error.
fn main() {
let greeting = "Hello";
println!("{}", greeting);
// greeting = "Hi"; // This line would cause an error if uncommented
}Trying to change an immutable variable causes a compile error in Rust.
Use immutable variables to make your code safer and easier to read.
Variables are immutable by default in Rust.
Immutable variables cannot be changed after they are set.
Use mut to make a variable mutable if needed.
immutable in Rust?count with value 10 in Rust?let mut variable_name = value;.let mut count = 10; uses the correct syntax. The other options use incorrect syntax.fn main() {
let x = 5;
// x = 10; // This line is commented out
println!("{}", x);
}x is declared as immutable with value 5. The reassignment line is commented out, so it does not execute.x, which remains 5.fn main() {
let x = 3;
x = 4;
println!("{}", x);
}x is declared immutable by default with let x = 3;.x = 4; causes a compile-time error because x is immutable.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.Pass the test and this pattern moves unknown