0
0
Rustprogramming~5 mins

Immutable variables in Rust

Choose your learning style9 modes available
Introduction

Immutable variables hold values that cannot change once set. This helps keep your program safe and predictable.

When you want to store a value that should not change accidentally.
When you want to make your code easier to understand by knowing some values stay the same.
When you want to avoid bugs caused by changing data.
When you want to share data safely between parts of your program.
Syntax
Rust
let variable_name = value;

By default, variables in Rust are immutable.

To make a variable mutable, you add mut after let.

Examples
This creates an immutable variable x with value 5.
Rust
let x = 5;
// x cannot be changed later
Immutable variable holding a string.
Rust
let name = "Alice";
// name is a string that cannot be changed
This shows how to make a variable mutable with mut.
Rust
let mut y = 10;
y = 15; // allowed because y is mutable
Sample Program

This program creates an immutable variable greeting and prints it. Trying to change it later would cause an error.

Rust
fn main() {
    let greeting = "Hello";
    println!("{}", greeting);
    // greeting = "Hi"; // This line would cause an error if uncommented
}
OutputSuccess
Important Notes

Trying to change an immutable variable causes a compile error in Rust.

Use immutable variables to make your code safer and easier to read.

Summary

Variables are immutable by default in Rust.

Immutable variables cannot be changed after they are set.

Use mut to make a variable mutable if needed.