Start learning free

LESSON 28 OF 679 · CALCULATIONS WITH NUMBERS

Increment & Decrement Operators in Rust

Lesson

In programming, increasing the value of a variable by 1 is so common, there is an operator designed to do that.

In Rust there is no ++ operator, so we add 1 with += 1 (the increment):

let mut number: i32 = 10;
number += 1; // short for number = number + 1

println!("{}", number); // Output: 11

There is also one such operator for decreasing the value of a variable by 1.

Rust has no -- operator either, so we subtract 1 with -= 1 (the decrement):

let mut number: i32 = 10;
number -= 1; // short for number = number - 1

println!("{}", number); // Output: 9

Postfix:

Some languages have a postfix form, number++, which increments and returns the value before incrementing. Rust has no such operator, but we can get the same effect by reading the value first and then incrementing:

let mut number: i32 = 10;

let old_number = number;
number += 1;

println!("{}", old_number); // Output: 10
println!("{}", number); // Output: 11

This code first assigns the value of number (which is 10) to old_number and then increments number (making it 11). It's equivalent to this:

let old_number = number;
number += 1;

Prefix:

Other languages also have a prefix form, ++number, which increments and returns the value after incrementing. In Rust we get that by incrementing first and then reading the value:

let mut number: i32 = 10;

number += 1;
let new_number = number;

println!("{}", new_number); // Output: 11
println!("{}", number); // Output: 11

This code first increments number (making it 11) and then assigns the new value of number to new_number (making it 11). It's equivalent to this:

number += 1;
let new_number = number;

Here's an example with the decrement operator:

let mut number: i32 = 10;

number -= 1;
let new_number = number;

println!("{}", new_number); // Output: 9
println!("{}", number); // Output: 9

Assignment
Follow the Coding Tutorial and let's practice with these operators!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 5
    Ctrl + Enter to check