Variables in Rust Language
A variable serves as a named storage unit that allows programs to manipulate data. In essence, variables facilitate the storage of values. In
A variable serves as a named storage unit that allows programs to manipulate data. In essence, variables facilitate the storage of values. In
In this section, we’ll explore the rules for naming variables:
When declaring a variable in Rust, the data type is optional, as it can be inferred from the assigned value. The syntax for variable declaration is as follows:
let variable_name = value; // No type specified
let variable_name: DataType = value; // Type specified
fn main() {
let fees = 25_000;
let salary: f64 = 35_000.00;
println!("fees is {} and salary is {}", fees, salary);
}
The output of the code above will be: “fees is 25000 and salary is 35000.”
By default, variables in Rust are immutable, meaning their values cannot be changed once they are bound to a variable name. Here’s an example to illustrate this:
fn main() {
let fees = 25_000;
println!("fees is {} ", fees);
fees = 35_000; // Error: Attempting to change an immutable variable.
println!("fees changed is {}", fees);
}
The output will result in an error message, indicating that re-assignment of an immutable variable like fees
is not allowed. This immutability is a fundamental feature of Rust, contributing to program safety and concurrent execution.
Variables are, by default, immutable in Rust. To make a variable mutable, you need to prefix its name with the mut
keyword. Mutable variables can have their values changed. The syntax for declaring a mutable variable is as follows:
let mut variable_name = value;
let mut variable_name: DataType = value;
Here’s an example:
fn main() {
let mut fees: i32 = 25_000;
println!("fees is {} ", fees);
fees = 35_000; // Changing the value of a mutable variable is allowed.
println!("fees changed is {}", fees);
}
The output of this code snippet will be:
fees is 25000
fees changed is 35000
Subscribe to get the latest posts sent to your email.