Start learning free

LESSON 26 OF 671 · CALCULATIONS WITH NUMBERS

Increment & Decrement Operators in Go

Lesson

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

That operator is the increment operator (++):

number := 10
number++ // short for number += 1

fmt.Println(number) // Output: 11

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

That operator is the decrement operator (--):

number := 10
number-- // short for number -= 1

fmt.Println(number) // Output: 9

Go uses increment and decrement as statements

In Go, number++ and number-- are statements. They change the variable, but they do not return a value.

That means this is valid:

number := 10
number++

But this is not valid Go:

oldNumber := number++ // invalid in Go
++number              // invalid in Go

Post-style behavior in Go

If you want to store the old value and then increment, do those two operations separately:

number := 10

oldNumber := number
number++

fmt.Println(oldNumber) // Output: 10
fmt.Println(number)    // Output: 11

Pre-style behavior in Go

If you want to increment first and then store the new value, write the increment before the assignment:

number := 10

number++
newNumber := number

fmt.Println(newNumber) // Output: 11
fmt.Println(number)    // Output: 11


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