In programming, it is common to use assignments to modify the contents of a variable.
Remember that everything to the right of the equals sign (=) is evaluated first, so we can say:
my_var = my_var + 5;
to add 5 to my_var.
Since this is such a common pattern, there are operators which do both a mathematical operation and assignment in one step.
One such operator is the += operator:
let mut my_var = 10;
my_var += 5;
println!("{}", my_var); // Output: 15
This code would print 15 to the console. We call my_var += 5 an augmented assignment.
There is one such operator for every other arithmetic operator we've learned:
For subtraction: -=
let mut my_var = 10;
my_var -= 5; // short for my_var = my_var - 5;
println!("{}", my_var); // Output: 5
For multiplication: *=
let mut my_var = 3;
my_var *= 5; // short for my_var = my_var * 5;
println!("{}", my_var); // Output: 15
For division: /=
let mut my_var = 20;
my_var /= 4; // short for my_var = my_var / 4;
println!("{}", my_var); // Output: 5
For remainder: %=
let mut my_var = 11;
my_var %= 3; // short for my_var = my_var % 3;
println!("{}", my_var); // Output: 2
Assignment
Follow the Coding Tutorial and let's do some augmented assignments.
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. Premium is unlimited.