Go Reference ยท Operators
Assignment: = and compound operators
Reference for Go assignment: plain =, compound operators like += and <<=, tuple assignment, swapping, blank identifier, ++ and -- statements.
Assignment stores a value in a variable, element, field or pointer target. The plain form is =. For every binary arithmetic, bitwise and shift operator there is a compound form (+=, -=, *=, /=, %=, &=, |=, ^=, &^=, <<=, >>=), and x op= y means x = x op y with x evaluated only once.
Assignment in Go is a statement, not an expression: you cannot write a = b = c or use an assignment as a condition. In exchange, Go supports tuple assignment, which assigns several values at once and makes swaps trivial.
a, b = b, a total += price * qty
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Syntax
lhs = rhs lhs1, lhs2 = rhs1, rhs2 lhs op= rhs // op is + - * / % & | ^ &^ << >> lhs++ // statement, same as lhs += 1 lhs--
| Name | Description |
|---|---|
lhs |
An addressable operand (variable, field of an addressable struct, slice element, pointer dereference) or a map index expression. The blank identifier _ is allowed on the left of =. |
rhs |
A value assignable to the type of lhs. |
Edge cases
- In a tuple assignment, the index expressions and pointer indirections on the left and all operands on the right are evaluated first, in the usual order; only then are the assignments carried out, left to right.
- The number of values on both sides must match, except when a single call, map index, type assertion or channel receive provides several.
- You cannot assign to a struct field of a map element (
m["a"].n = 1is a compile error); copy the struct, change it, and store it back. - Compound assignment on a map element works:
m[k] += 1reads the zero value for a missing key.
Usage notes
x++andx--are statements, not expressions. There is no prefix form andy = x++does not compile.- Assigning does not convert types:
var f float64 = ifails wheniis anint. Convert explicitly withfloat64(i). - Assigning a slice, map, channel, pointer or function copies the reference, not the underlying data. Arrays and structs are copied by value.
- Use
:=only to declare;=to change an existing variable. Ina, err := f()at least one name on the left must be new, and the others are assigned. See :=. - Integer division and
%panic at run time when the right side is 0. Floating-point division gives infinity or NaN. - Compound shifts such as
x <<= nfollow the rules on << and >>.