Rust mutable
Created By: chatGPT
In Rust, a variable is immutable by default. To make a variable mutable, you need to use the
mut
keyword. This allows you to change the value of the variable after it has been initialized. Here's an example: fn main() {
let mut x = 5; // x is mutable
println!("Value of x: {}", x);
x = 10; // x can be changed
println!("New value of x: {}", x);
}
In this snippet, we declare a mutable variable
x
and reassign its value later. If you tried to reassign an immutable variable, the compiler would throw an error.fn main() {
let y = 5; // y is immutable
println!("Value of y: {}", y);
// y = 10; // This would cause an error!
}
Mutability can also apply to data structures, such as arrays or vectors. For example, you can have a mutable vector and change its contents:
fn main() {
let mut vec = vec![1, 2, 3]; // mutable vector
println!("Vector before: {:?}", vec);
vec.push(4); // push a new value
println!("Vector after: {:?}", vec);
}
Keep in mind that mutability is scoped. Even if a variable is declared as mutable, it will only be mutable within its scope. After leaving its scope, it cannot be modified.
fn main() {
let mut z = 5;
{
z += 1; // This works
}
// z = z + 1; // Still works
}