A Guide To Variables and Mutability In Rust Programming

In computer system programming, we can use variables to store data. For example-

let x = 1;

Above, x is name of the variable which stores the value 1.

We can think of variables as containers that maintain information.

Variable Declaration In Rust :

In Rust Programming , we declare variables by using the let keyword. Rust Program is a statically-typed language, that means we need to specify the type of the variable at the time of declaration, or the compiler must be capable to infer the type. Please see a basic example of variable declarations in Rust:

fn main() {
    // Immutable variable (by default)
    let x: i32 = 42;
    println!("Immutable variable x: {}", x);

    // Mutable variable
    let mut y: f64 = 3.14;
    println!("Mutable variable y: {}", y);

    // Reassigning a mutable variable
    y = 2.718;
    println!("Updated value of y: {}", y);

    // Type inference (compiler can deduce the type)
    let z = "Hello, Rust!";
    println!("Inferred type variable z: {}", z);
}

Example:

  1. x is an immutable variable type i32 (32-bit signed integer). 2. y is a mutable variable type f64 (64-bit floating-point number). 3. The mut keyword is used to create a variable mutable. 4. z is a variable with type of inference; the compiler guess that it’s a string slice (&str) in this case.

Note: that variables are immutable by default in Rust Program, and we need to use mut apparently to create them mutable. This design like aligns with Rust’s emphasis on security and prohibiting unintended side effects. Immutable variables help avoid adventitious changes and make it easy to reason about the code.

You can use the let keyword to declare a variable in Rust.

let age = 21;

Above, you have created a variable named age with value 21.

Example: Variables In Rust

fn main() {
    // variable to store integer value
    let age = 21;
    println!("Age: {}", age);

    // variable to store floating-point value
    let salary = 42523.2;
    println!("Salary: {}", salary);

    // variable to store string
    let name = "Akash";
    println!("Name: {}", name);
}

Output :

Age: 21
Salary: 42523.2
Name: Akash

In the upon example, you have created three different variables :-

  1. age - to store an integer value.
  2. salary - to store a floating-point data.
  3. name - to store a string.

Follow that we have used println! macro to print the variables.

println!("Age: {}", age);

Change Value of a Variable In Rust :

By disability, Rust variables are constant, that means yo cannot change the value of a variable once it is defined. Let’s see an example-

fn main() {
    // declare a variable with value 1
    let x = 1;
    println!("x = {}", x);

    // change the value of variable x
    x = 2;
    println!("x = {}", x);
}

Follow the example when you run this code, yo will get an error. Because you are trying to change the value of the x variable from 1 to 2.

error[E0384]: cannot assign twice to immutable variable `x`
 --> main.rs:7:5
  |
3 |     let x = 1;
  |         -
  |         |
  |         first assignment to `x`
  |         help: consider making this binding mutable: `mut x`
...
7 |     x = 2;
  |     ^^^^^ cannot assign twice to immutable variable

For solve this error, Rust allows you to create mercurial variables.

Mutability in Rust Program :

In Rust programming, mutability is a key of idea that relates to whether a variable’s value can be reciprocal after it has been assigned. Rust program is schematic to be a statically-typed and strongly-typed language that provides a high level of control over safety memory without sacrificing performance. Please see below how mutability works in Rust:

Declaring Variables In Rust:

In Rust Programming, variables are unchangeable by default. This cause that once a value is assigned to a variable, by default, we cannot change that value. below an example:

fn main() {
    let x = 5; // Immutable variable
    println!("The value of x is: {}", x);
    
    // This would result in a compilation error:
    // x = 10;
}

Mutable Variables In Rust:

To create a variable mutable, we need to use the mut keyword. This agree you to change the value of the variable then it has been assigned:

fn main() {
    let mut y = 10; // Mutable variable
    println!("The value of y is: {}", y);
    
    y = 20; // This is allowed for mutable variables
    println!("Now the value of y is: {}", y);
}

Output :

The value of y is: 10
Now the value of y is: 20

Mutable References In Rust:

When we working with references, we need to explicitly use the &mut syntax to create mutable references. This agree we to modify the value through the reference:

fn main() {
    let mut z = 15;
    println!("The original value of z is: {}", z);

    let z_ref = &mut z; // Mutable reference
    *z_ref = 25; // Dereferencing the mutable reference and modifying the value

    println!("Now the value of z is: {}", z);
}

Output :

The original value of z is: 15
Now the value of z is: 25

Benefits of Immutability In Rust

Rust’s property on immutability by default helps obstruct certain types of bugs and makes the code more predictable sequence. It contribute to Rust’s ownership system, quality the compiler to enforce memory safety without the need for a rubbish collector

Naming Variables Rules In Rust :

When we are working with references, you need to apparently use the &mut syntax to create mutable references. This agree you to modify the value through the reference:

fn main() {
    let mut z = 15;
    println!("The original value of z is: {}", z);

    let z_ref = &mut z; // Mutable reference
    *z_ref = 25; // Dereferencing the mutable reference and modifying the value

    println!("Now the value of z is: {}", z);
}

You can use any names as variable names, but, there are some rules you should follow this :-

  1. Rust is a case impressible language. So, lowercase variables and uppercase variables are several. For example :-
  • age is several from AGE

  • name is several from Name

  1. Variables must will be start with either a letter or an underscore. For example,
let age = 21;     	// valid and good practice
let _age = 21;    	// valid variable 
let 1age = 21;    // inavlid variable
  1. Variable names can only take on letters, digits & an underscore character. For example :-
let age1 = 21;        // valid variable
let age_num = 21;     // valid variable
let s@lary = 52352;   // invalid variable
  1. Now Use underscore if you need to use two words as variable names. For example :-
let first name = "Akash";    // invalid variable
let first_name = "Akash";    // valid variable
let first-name = "Akash";    // invalid variable

Constants In Rust :

Certain is a special type of variable which value cannot be changed. You can use the const keyword to create constants in Rust. For example :-

fn main() {
    // declare a float constant
    const PI: f32 = 3.14;

    println!("Value of PI = {}", PI);
}

Output :

Value of PI = 3.14

Here the example, you have declared a constant PI with value 3.14. Now, the value of PI cannot be changed unique the program.

Now let’s see what happens if you try to change the value of a constant.

fn main() {
    // declare a constant
    const PI:f32 = 3.14;
    println!("Initial Value of PI: {}", PI);

    // change value of PI
    PI = 535.23;
    println!("Update Value of PI: {}", PI);
}

Whereas you run this code, you will get an error because PI is a constant.

error[E0070]: invalid left-hand side of assignment
 --> main.rs:7:8
  |
7 |     PI = 535.23;
  |     -- ^
  |     |
  |     cannot assign to this expression
Previous
A Guide to Optimizing Print Output in Your Rust Programming
Next
Exploring Rust Data Types: A Comprehensive Guide for Developers