In Rust, declaring and initializing variables is primarily done using the let keyword. Rust variables are immutable by default, meaning that once a variable is assigned a value, its value cannot be changed unless you explicitly specify it as mutable using the mut keyword.
Declaring Immutable Variables
To declare an immutable variable in Rust, use the following syntax:
rustlet variable_name = value;
For example, declaring an immutable integer variable:
rustlet x = 5;
In this example, x is an immutable integer variable initialized to 5.
Declaring Mutable Variables
If you need to modify a variable's value, declare it as mutable using the mut keyword:
rustlet mut variable_name = value;
For example, declaring a mutable integer variable:
rustlet mut y = 5; y = 10; // Correct, as y is mutable
In this example, y is initially set to 5 and then changed to 10.
Using Type Annotations
Although Rust can infer variable types automatically, you may explicitly specify them using type annotations:
rustlet variable_name: type = value;
For example, explicitly declaring an integer variable:
rustlet z: i32 = 20;
In this example, z is explicitly declared as a 32-bit integer and initialized to 20.
Summary
By using the let keyword (along with optional mut and type annotations), you can flexibly declare and initialize variables in Rust. Immutability (the default behavior) helps prevent errors and inconsistencies in the code, while mutability can be enabled through explicit declaration when needed. These features make Rust both safe and flexible.