Arithmetic Shortcuts
Part of the Fundamentals section of Coddy's Rust journey — lesson 17 of 75.
Rust created a cool shortcut for self-arithmetic operations.
For example instead of writing:
let mut a: i32 = 5;
a = a + 3; // a holds 8We can simplify it by writing +=:
let mut a: i32 = 5;
a += 3; // a holds 8The += is adding to a itself the value 3
This operation is valid for all arithmetic operations:
| Operator | Shortcut |
|---|---|
| + | += |
| - | -= |
| * | *= |
| / | /= |
| % | %= |
Challenge
BeginnerYou are given a code with initialization of count. (Don't delete this line!)
Your task is to add the following operations, in this order:
- Add
4tocount - Multiply
countby2 - Subtract
1fromcount
Use the arithmetic shortcuts to do so!
Cheat sheet
Rust provides shortcut operators for self-arithmetic operations:
| Operator | Shortcut |
|---|---|
| + | += |
| - | -= |
| * | *= |
| / | /= |
| % | %= |
Instead of writing:
let mut a: i32 = 5;
a = a + 3; // a holds 8You can use the shortcut:
let mut a: i32 = 5;
a += 3; // a holds 8Try it yourself
fn main() {
let mut count: i32 = 0;
// Type your code below
// Don\'t change the line below
println!("count = {}", count);
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsComparison OperatorsString Comparison5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 33Variables Part 2
Type DeclarationNaming ConventionsType InferenceRecap - Initialize VariablesType Casting9Loops
For Over SeriesWhile LoopBreakContinueNested LoopLoop LabelsInfinite LoopRecap - Dynamic Input