0
0
Rustprogramming~5 mins

Assignment operators in Rust

Choose your learning style9 modes available
Introduction
Assignment operators help you store or update values in variables easily.
When you want to save a value in a variable.
When you want to add or subtract a number from a variable's current value.
When you want to multiply or divide a variable by a number and save the result.
When you want to combine updating and assigning a value in one step.
Syntax
Rust
let mut variable = value;
variable = new_value; // simple assignment
variable += value; // add and assign
variable -= value; // subtract and assign
variable *= value; // multiply and assign
variable /= value; // divide and assign
variable %= value; // remainder and assign
Variables must be declared with mut to allow changing their value.
Assignment operators combine an operation and assignment in one step.
Examples
Assign a new value 10 to variable x.
Rust
let mut x = 5;
x = 10;
Add 3 to x and save the result back to x.
Rust
let mut x = 5;
x += 3; // x is now 8
Multiply x by 2 and save the result.
Rust
let mut x = 10;
x *= 2; // x is now 20
Assign the remainder of x divided by 3 back to x.
Rust
let mut x = 10;
x %= 3; // x is now 1
Sample Program
This program shows how to use different assignment operators to update the variable score step by step.
Rust
fn main() {
    let mut score = 10;
    println!("Initial score: {}", score);
    score += 5;
    println!("After adding 5: {}", score);
    score *= 2;
    println!("After doubling: {}", score);
    score -= 4;
    println!("After subtracting 4: {}", score);
    score /= 3;
    println!("After dividing by 3: {}", score);
    score %= 3;
    println!("After remainder by 3: {}", score);
}
OutputSuccess
Important Notes
Remember to declare variables with mut if you want to change their values.
Assignment operators make code shorter and easier to read when updating variables.
Using assignment operators is like doing math and saving the answer back to the same box.
Summary
Assignment operators store or update values in variables.
Use +=, -=, *=, /=, and %= to combine math and assignment.
Variables must be mutable (mut) to use assignment operators.