Operators#
Go’s operator set covers arithmetic, comparison, logical,
bitwise, pointer (& *), and channel (<-) operations.
There is no operator overloading; types decide their own
semantics through methods, not by overriding operators.
/types`.
Arithmetic#
Operator |
Meaning |
|---|---|
|
addition; on strings, concatenation |
|
subtraction (and unary negation) |
|
multiplication |
|
division; integer-truncating between integers |
|
modulo (sign follows dividend); valid only on integers |
|
increment / decrement. Statement only; cannot appear inside an expression. |
7 / 2 // 3 (integer division)
7.0 / 2 // 3.5
7 % 2 // 1
"hello, " + name // concatenation
i++ // statement; not an expression
Relational#
== != < <= > >= work on comparable types (all numerics,
strings, pointers, channels, interface values, structs of
comparable fields, fixed arrays of comparable elements). Slices
and maps are not comparable except against nil.
1 == 1 // true
"abc" < "abd" // true (lexicographic)
s == nil // valid for slices
m == nil // valid for maps
xs == ys // compile error if slices
For deep equality, reflect.DeepEqual or
slices.Equal / maps.Equal.
Logical#
&& and || short-circuit. ! is unary.
if x > 0 && y > 0 { /* … */ }
if v, ok := m[k]; ok { use(v) } // also: && pattern with init
Bitwise#
Operator |
Meaning |
|---|---|
|
AND |
|
OR |
|
XOR (binary) / bitwise complement (unary) |
|
AND-NOT (Go’s “bit clear” operator) |
|
left shift |
|
right shift (arithmetic for signed, logical for unsigned) |
0xff & 0x0f // 15
1 << 8 // 256
flags &^ Verbose // clear the Verbose bit
Assignment#
= assigns; compound forms exist (+= -= *= /= %= &= |=
^= <<= >>= &^=). Short declaration := declares plus
assigns.
x = 1
x += 2
x, y = y, x
x, y := 1, 2 // short declaration; only inside functions
Pointer#
& takes the address; * dereferences.
var x int = 10
p := &x // *int
*p = 20 // x is now 20
u := &User{Name: "rk"}
u.Name = "operator" // auto-deref on field access
Go has no pointer arithmetic. The operator cannot p++ a
pointer; unsafe.Pointer is the back-door, used rarely and
carefully.
Channel#
ch <- v sends; <-ch receives.
ch := make(chan int, 1)
ch <- 42 // send
v := <-ch // receive
v, ok := <-ch // ok=false when the channel is closed and empty
close(ch) // close (only the sender closes)
See Concurrency for select and the full surface.
Precedence#
Highest to lowest.
Group |
Operator |
|---|---|
5 |
|
5 |
|
5 |
|
5 |
|
5 |
|
5 |
|
5 |
|
4 |
|
4 |
|
4 |
|
4 |
|
3 |
|
3 |
|
3 |
|
3 |
|
3 |
|
3 |
|
2 |
|
1 |
|
Unary operators (+, -, !, ^, *, &) bind
tighter than any binary operator. The operator parenthesises
ambiguous expressions; the compiler does not warn.
References#
Types for which types support which operators.
Control flow for
selectand the conditions operators feed.Concurrency for channel send / receive semantics.