๐ŸŽ“ A1Learner
๐Ÿ”

Go Operators

Operators are symbols that change or combine values. Assignment operators update a variable by using its current value.

Adding and taking one

The ++ statement raises the value by 1. The -- statement lowers it by 1.

package main

import "fmt"

func main() {
	count := 5
	count++
	fmt.Println(count)
	count--
	fmt.Println(count)
}

Updating in place

The += operator adds 6 to the total. The *= operator then multiplies the total by 3.

package main

import "fmt"

func main() {
	total := 4
	total += 6
	fmt.Println(total)
	total *= 3
	fmt.Println(total)
}

The remainder

The % operator gives what is left after division. Ten divided by three leaves one.

package main

import "fmt"

func main() {
	fmt.Println(10 % 3)
}

Parentheses change the order

Multiplication runs before addition in the first print. The parentheses make the addition run first in the second print.

package main

import "fmt"

func main() {
	fmt.Println(2 + 3*4)
	fmt.Println((2 + 3) * 4)
}

Example

package main

import "fmt"

func main() {
	items := 2
	items += 3
	fmt.Println("Items:", items)
	items *= 2
	fmt.Println("Doubled:", items)
	fmt.Println("Left over:", items%3)
}

Key points

  • The ++ statement adds 1 to a variable.
  • The -- statement takes 1 away from a variable.
  • The += operator adds a value and stores the result.
  • The *= operator multiplies a value and stores the result.
  • The % operator gives the remainder after division.
  • Parentheses change the order in which sums are worked out.

In this example, items starts at 2. The += operator adds 3, so items holds 5. The *= operator doubles that value to 10. The last print shows the remainder when 10 is split into groups of 3.

Note

++ and -- are statements in Go, so each one stands on its own line.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Go Playground

Exercise

What is the value of x after x := 5 and then x++?