Skip to main content

Assignment Operators

To store a value in a variable, you use an assignment operator.

The simplest is assignment itself (=). Here, a variable named x receives the value 10:

Example

Prompt
Use the assignment operator to set a variable to 10 and print it.
Output: Go program and captured output

Addition Assignment

With addition assignment (+=), a variable grows by the amount you give it, and the new total stays in that variable:

Example

Prompt
Use the addition assignment operator to add 5 to a variable and print the result.
Output: Go program and captured output

All Assignment Operators

Apart from plain =, each of these does a calculation first and then stores the result back in the variable:

  • = stores a value. Example: x = 5
  • += adds, then stores. Equivalent to x = x + 3
  • -= subtracts, then stores. Equivalent to x = x - 3
  • *= multiplies, then stores. Equivalent to x = x * 3
  • /= divides, then stores. Equivalent to x = x / 3
  • %= takes the modulus, then stores. Equivalent to x = x % 3
  • &= applies bitwise AND, then stores. Equivalent to x = x & 3
  • |= applies bitwise OR, then stores. Equivalent to x = x | 3
  • ^= applies bitwise XOR, then stores. Equivalent to x = x ^ 3
  • >>= shifts right, then stores. Equivalent to x = x >> 3
  • <<= shifts left, then stores. Equivalent to x = x << 3