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
main.go
package main
import ("fmt")
func main() {
var x = 10
fmt.Println(x)
}
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
main.go
package main
import ("fmt")
func main() {
var x = 10
x += 5
fmt.Println(x)
}
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 tox = x + 3-=subtracts, then stores. Equivalent tox = x - 3*=multiplies, then stores. Equivalent tox = x * 3/=divides, then stores. Equivalent tox = x / 3%=takes the modulus, then stores. Equivalent tox = x % 3&=applies bitwise AND, then stores. Equivalent tox = x & 3|=applies bitwise OR, then stores. Equivalent tox = x | 3^=applies bitwise XOR, then stores. Equivalent tox = x ^ 3>>=shifts right, then stores. Equivalent tox = x >> 3<<=shifts left, then stores. Equivalent tox = x << 3