Variables in Rust Language

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

st_(programming_language)">Rust, variables are associated with specific data types. These data types determine various aspects of the variable, including the size and memory layout, the range of values it can store, and the operations permitted on the variable.

Rules for Naming Variables in Rust Language

In this section, we’ll explore the rules for naming variables:

  1. The name of a variable can consist of letters, digits, and underscores.
  2. It must commence with either a letter or an underscore.
  3. Rust is case-sensitive, meaning uppercase and lowercase letters are distinct.

Syntax in Rust Language

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

Illustration in Rust Language

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.”

Immutable in Rust Language

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.

Mutable in Rust Language

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

Discover more from PiEmbSysTech

Subscribe to get the latest posts sent to your email.

Leave a Reply

Scroll to Top

Discover more from PiEmbSysTech

Subscribe now to keep reading and get access to the full archive.

Continue reading