Variables and Mutability
In Rust, variables are immutable by default. This means once you assign a value to a variable, you can't change it. This might seem restrictive at first, but it's actually a safety feature. When you know a value won't change, you can reason about your code more easily and avoid certain types of bugs.
If you need to change a variable, you can make it mutable by adding the mut keyword. Rust also does type inference, which means it can figure out the type of a variable based on the value you assign to it. You can also explicitly specify the type using a colon.
There are also constants in Rust, which are declared with the const keyword. Constants must have their type annotated and can't be changed. Another interesting feature is shadowing, where you can re-declare a variable with the same name using let. This can be useful when you need to change the type of a variable.
fn main() {
// Immutable by default
let x = 5;
println!("x is: {}", x);
// Make it mutable with 'mut'
let mut y = 10;
println!("y is: {}", y);
y = 20;
println!("y is now: {}", y);
// Type inference
let z = "hello"; // Rust knows this is a string slice
let a: i32 = 42; // Explicit type annotation
// Constants
const MAX_POINTS: u32 = 100_000;
println!("Max points: {}", MAX_POINTS);
// Shadowing - re-declaring with let
let spaces = " "; // string
let spaces = spaces.len(); // now it's a usize
println!("Spaces: {}", spaces);
}
Try it Yourself ->