0
0
Rustprogramming~5 mins

Why variables are needed in Rust

Choose your learning style9 modes available
Introduction

Variables let us store and name information so we can use it later in our program. They help keep data organized and easy to change.

When you want to remember a number or word to use multiple times.
When you need to change a value during the program, like counting steps.
When you want to give a meaningful name to a piece of data to make your code easier to understand.
When you want to store user input to use it later.
When you want to hold results of calculations to use again.
Syntax
Rust
let variable_name = value;

Use let to create a variable in Rust.

By default, variables are immutable (cannot change). Use let mut to make them changeable.

Examples
This creates an immutable variable x with the value 5.
Rust
let x = 5;
This creates a mutable variable count starting at 0 that can be changed later.
Rust
let mut count = 0;
This stores the text "Alice" in the variable name.
Rust
let name = "Alice";
Sample Program

This program shows how a variable steps stores a number that changes as we add 1 to it.

Rust
fn main() {
    let mut steps = 0;
    println!("Steps: {}", steps);
    steps = steps + 1;
    println!("Steps after walking: {}", steps);
}
OutputSuccess
Important Notes

Variables help keep your program flexible and readable.

Remember to use mut if you want to change a variable's value.

Summary

Variables store data with a name to use later.

Use let to create variables in Rust.

Use mut to make variables changeable.