Operators

suggest change

Go has a small, regular set of operators. Most of them look like C, but there are some differences:

Here are all of them, grouped by category:

Category Operators
Arithmetic + - * / %
Comparison == != < <= > >=
Logical && || !
Bitwise & | ^ &^ << >>
Unary + - ! ^ & * <-
Assignment = := += -= *= /= %= &= |= ^= &^= <<= >>=
Increment, decrement ++ --

Arithmetic operators

+, -, * and / work on integers, floating-point and complex numbers. % (remainder) only works on integers. + also concatenates strings:

package main

import "fmt"

func main() {
	a, b := 17, 5
	fmt.Println("a + b =", a+b)
	fmt.Println("a - b =", a-b)
	fmt.Println("a * b =", a*b)
	fmt.Println("a / b =", a/b)
	fmt.Println("a % b =", a%b)

	x, y := 17.0, 5.0
	fmt.Println("x / y =", x/y)

	s := "Hello, " + "World"
	s += "!"
	fmt.Println(s)

	n := 7
	fmt.Println(-n, +n)
}
a + b = 22
a - b = 12
a * b = 85
a / b = 3
a % b = 2
x / y = 3.4
Hello, World!
-7 7

Notice that 17 / 5 is 3: division of integers produces an integer.

Building a long string with += in a loop creates a new string every time. Use strings.Builder for that.

Integer division and remainder

Integer division truncates towards zero, and the remainder has the sign of the dividend (the left operand). This is the same as C and Java, but different from Python, which floors:

package main

import (
	"fmt"
	"math"
)

func main() {
	fmt.Println(7/2, -7/2)
	fmt.Println(7%3, -7%3, 7%-3, -7%-3)

	// floor division and always-positive modulo
	fmt.Println(floorMod(-7, 3))
	fmt.Println(math.Floor(-7.0 / 2))

	// % is only for integers, use math.Mod for floats
	fmt.Println(math.Mod(7.5, 2))
}

func floorMod(a, b int) int {
	m := a % b
	if m != 0 && (m < 0) != (b < 0) {
		m += b
	}
	return m
}
3 -3
1 -1 1 -1
2
-4
1.5

The rule that always holds is (a / b) * b + a % b == a.

A common bug: i % n can be negative when i is negative, so it's not a safe index into a slice. Use floorMod (or make sure i is non-negative) when wrapping around a ring buffer.

Division by zero

Integer division by zero panics at runtime. Floating-point division by zero follows IEEE 754 and produces infinity or NaN:

package main

import "fmt"

func divide(a, b int) (res int, err error) {
	defer func() {
		if r := recover(); r != nil {
			err = fmt.Errorf("%v", r)
		}
	}()
	return a / b, nil
}

func main() {
	_, err := divide(10, 0)
	fmt.Println("int:", err)

	zero := 0.0
	fmt.Println("float:", 1/zero, -1/zero, zero/zero)
}
int: runtime error: integer divide by zero
float: +Inf -Inf NaN

If the divisor is a constant zero, the compiler catches it: 10 / 0 is a compile error invalid operation: division by zero.

In real code, check the divisor before dividing instead of relying on recover.

Integer overflow

Integer arithmetic silently wraps around. There's no overflow panic and no undefined behavior, the result is just the low bits of the true result:

package main

import (
	"fmt"
	"math"
)

func main() {
	var u uint8 = 255
	u++
	fmt.Println("uint8 255+1 =", u)

	var i int8 = 127
	i++
	fmt.Println("int8 127+1 =", i)

	var m int32 = math.MinInt32
	fmt.Println("-MinInt32 =", -m)
	fmt.Println("MinInt32 / -1 =", m/-1)
}
uint8 255+1 = 0
int8 127+1 = -128
-MinInt32 = -2147483648
MinInt32 / -1 = -2147483648

Constant expressions are different. They are evaluated at compile time with arbitrary precision, and overflowing the type is a compile error: var x int8 = 127 + 1 doesn't compile.

If you need to detect overflow, you have to check for it yourself:

package main

import (
	"fmt"
	"math"
	"math/bits"
)

func addChecked(a, b int64) (int64, bool) {
	c := a + b
	// overflow happened if both operands have the same sign
	// and the result has a different sign
	if (c > a) != (b > 0) {
		return c, false
	}
	return c, true
}

func main() {
	fmt.Println(addChecked(1, 2))
	fmt.Println(addChecked(math.MaxInt64, 1))

	sum, carry := bits.Add64(math.MaxUint64, 1, 0)
	fmt.Println(sum, carry)

	var x uint16 = 0b0000_1011_0000_0000
	fmt.Println(bits.OnesCount16(x), bits.LeadingZeros16(x), bits.TrailingZeros16(x))
	fmt.Printf("%016b\n", bits.RotateLeft16(x, 4))
	fmt.Println(bits.Len(1000)) // bits needed to represent 1000
}
3 true
-9223372036854775808 false
0 1
3 4 8
1011000000000000
10

Package math/bits also has Mul64, Sub64 and Div64 with carry/borrow, plus bit counting and rotation functions that compile to single CPU instructions. For numbers that don't fit in 64 bits, use big.Int.

Operands must have the same type

Go never converts between numeric types implicitly. Adding an int32 to an int64, or an int to a float64, is a compile error. You have to convert explicitly:

package main

import "fmt"

func main() {
	var a int32 = 10
	var b int64 = 20
	// fmt.Println(a + b) // invalid operation: a + b (mismatched types int32 and int64)
	fmt.Println(int64(a) + b)

	n := 3
	f := 1.5
	fmt.Println(float64(n) * f)

	// untyped constants adapt to the other operand
	fmt.Println(f * 2)
	fmt.Println(n/2, n/2.0)
}
30
4.5
3
1 1

The last line is a trap: n/2.0 is still integer division. The untyped constant 2.0 is converted to int, the type of n. It works because 2.0 has no fractional part. n * 1.5 doesn't compile: 1.5 (untyped float constant) truncated to int.

See Type casting and Typed vs. untyped constants for more.

Comparison operators

== and != work on all comparable types: booleans, numbers, strings, pointers, channels, interfaces, and arrays and structs made of comparable types. <, <=, > and >= work on integers, floats and strings. Strings are compared byte by byte, so "Z" < "a".

The result of a comparison is an untyped boolean.

fmt.Println(3 < 5, 3 == 5, 3 != 5, "apple" < "banana", "Z" < "a")
true false true true true

Slices, maps and functions can only be compared to nil. The details, including comparing floats, interfaces and structs, are in Equality and comparison.

Logical operators

&& (and), || (or) and ! (not) only work on bool values. Unlike C, an integer or a pointer is not a condition: if n { is a compile error non-boolean condition in if statement. Write if n != 0 { or if p != nil {.

&& and || short-circuit: the right operand is only evaluated when needed.

package main

import "fmt"

func check(name string, v bool) bool {
	fmt.Println("  evaluating", name)
	return v
}

func main() {
	fmt.Println("false && ...:")
	r := check("left", false) && check("right", true)
	fmt.Println("  result:", r)

	fmt.Println("true || ...:")
	r = check("left", true) || check("right", false)
	fmt.Println("  result:", r)

	fmt.Println(!true, !(3 > 5))

	// short-circuit as a guard
	var m map[string][]int
	if v, ok := m["k"]; ok && len(v) > 0 {
		fmt.Println(v[0])
	} else {
		fmt.Println("no value")
	}
}
false && ...:
  evaluating left
  result: false
true || ...:
  evaluating left
  result: true
false true
no value

Short-circuiting is what makes guards like p != nil && p.Name == "x" or i < len(s) && s[i] == ' ' safe.

Bitwise operators

Bitwise operators work on integers:

Operator Name Result bit is 1 when
a & b AND both bits are 1
a | b OR at least one bit is 1
a ^ b XOR bits are different
a &^ b AND NOT (bit clear) bit is 1 in a and 0 in b
^a NOT (complement) bit in a is 0

Go uses ^ for both XOR (binary) and bitwise NOT (unary). There's no ~ operator for integers (~ only appears in generic type constraints).

package main

import "fmt"

func main() {
	a, b := uint8(0b1100_1010), uint8(0b1010_0110)
	fmt.Printf("a      = %08b\n", a)
	fmt.Printf("b      = %08b\n", b)
	fmt.Printf("a & b  = %08b\n", a&b)
	fmt.Printf("a | b  = %08b\n", a|b)
	fmt.Printf("a ^ b  = %08b\n", a^b)
	fmt.Printf("a &^ b = %08b\n", a&^b)
	fmt.Printf("^a     = %08b\n", ^a)

	fmt.Println(^0, ^5, ^int8(-1))
}
a      = 11001010
b      = 10100110
a & b  = 10000010
a | b  = 11101110
a ^ b  = 01101100
a &^ b = 01001000
^a     = 00110101
-1 -6 0

For signed integers ^x equals -x - 1, which is why ^5 is -6.

Bit flags

Bitwise operators are most often used for sets of flags. Combine iota with << to give each flag its own bit, then use |= to set, &^= to clear, ^= to toggle and & to test:

package main

import "fmt"

type Perm uint8

const (
	Read Perm = 1 << iota
	Write
	Exec
)

func (p Perm) String() string {
	s := []byte("---")
	if p&Read != 0 {
		s[0] = 'r'
	}
	if p&Write != 0 {
		s[1] = 'w'
	}
	if p&Exec != 0 {
		s[2] = 'x'
	}
	return string(s)
}

func main() {
	var p Perm
	p |= Read | Write // set bits
	fmt.Println(p)
	p |= Exec
	fmt.Println(p)
	p &^= Write // clear bit
	fmt.Println(p)
	p ^= Read // toggle bit
	fmt.Println(p)
	fmt.Println("has exec:", p&Exec != 0)
}
rw-
rwx
r-x
--x
has exec: true

p&Exec != 0 doesn't need parentheses. In Go & has higher precedence than !=, the opposite of C, where p & Exec != 0 means p & (Exec != 0).

Shift operators

x << n shifts bits left (multiplies by 2^n) and x >> n shifts right (divides by 2^n, rounding towards negative infinity).

Right shift of a signed integer is arithmetic (copies the sign bit), right shift of an unsigned integer is logical (fills with zeros). Bits shifted out of the type are lost:

package main

import "fmt"

func main() {
	fmt.Println(1<<10, 1024>>3)

	x := int8(-16)
	fmt.Println(x>>2, uint8(x)>>2) // arithmetic vs logical shift

	var u uint8 = 1
	fmt.Println(u<<7, u<<8) // bits shifted out are lost

	n := 3
	fmt.Println(1 << n) // shift count can be any integer type

	defer func() { fmt.Println("recovered:", recover()) }()
	n = -1
	fmt.Println(1 << n)
}
1024 128
-4 60
128 0
8
recovered: runtime error: negative shift amount

Shifting by the type's width or more is well defined in Go: it gives 0 (or -1 for a right shift of a negative number). In C it's undefined behavior.

The shift count can be a signed integer, but a negative count panics at runtime.

There's one subtle rule: in a non-constant shift, an untyped constant on the left takes the type it would have without the shift. So var f float64 = 1 << s (where s is a variable) fails to compile with shifted operand 1 (type float64) must be integer. Write float64(1 << s) instead.

Assignment operators

Every binary arithmetic and bitwise operator has an assignment form: x op= y is the same as x = x op y, except x is evaluated only once.

package main

import "fmt"

func main() {
	x := 10
	x += 5
	x -= 3
	x *= 2
	x /= 4
	x %= 4
	fmt.Println(x)

	y := 0b1111
	y <<= 2
	y &= 0b111100
	y >>= 1
	y |= 1
	y ^= 0b10
	fmt.Println(y)

	i := 0
	i++
	i++
	i--
	fmt.Println(i)

	arr := []int{1, 2, 3}
	arr[0]++
	m := map[string]int{}
	m["hits"]++
	m["hits"] += 10
	fmt.Println(arr, m)
}
2
29
1
[2 2 3] map[hits:11]

m["hits"]++ works on a missing key because reading a missing key returns the zero value.

= assigns to existing variables, := declares new variables and assigns them. See Basic variable declaration and Multiple variable assignment.

++ and -- are statements

i++ and i-- are statements. You can't use them in an expression, and there's no prefix ++i:

j := i++ // syntax error: unexpected ++ at end of statement
++i      // syntax error: unexpected ++, expected }

This removes a whole class of C puzzles like a[i] = i++. If you need the old value, write it out:

j := i
i++

Pointer and channel operators

Unary & takes the address of a variable (or of a composite literal), unary * dereferences a pointer. <- sends a value to a channel (ch <- v) or receives one (<-ch).

package main

import "fmt"

func main() {
	// unary & takes an address, unary * dereferences
	n := 42
	p := &n
	*p += 8
	fmt.Println(n, *p == n)

	type point struct{ X, Y int }
	pt := &point{1, 2}
	pt.X = 10 // same as (*pt).X = 10
	fmt.Println(*pt)

	// <- sends to and receives from a channel
	ch := make(chan int, 1)
	ch <- 7
	v, ok := <-ch
	fmt.Println(v, ok)
}
50 true
{10 2}
7 true

There's no pointer arithmetic and no -> operator: pt.X automatically dereferences a pointer to a struct. More in Pointers and Channels.

Operator precedence

Unary operators have the highest precedence. Binary operators have 5 levels:

Precedence Operators
5 (highest) * / % << >> & &^
4 + - | ^
3 == != < <= > >=
2 &&
1 (lowest) ||

Operators of the same precedence are evaluated left to right. The way to remember it: "multiplicative" operators (including shifts and AND) are at level 5 and "additive" operators (including OR and XOR) are at level 4.

package main

import "fmt"

func main() {
	fmt.Println(2 + 3*4) // * before +
	fmt.Println((2 + 3) * 4)
	fmt.Println(1 + 2<<3) // << is level 5, same as *
	fmt.Println(6&3 + 1)  // & is level 5 too: (6&3)+1
	fmt.Println(-2 * -3)
	fmt.Println(10 - 4 - 3) // left to right
	fmt.Println(100 / 10 / 5)

	x := 5
	fmt.Println(x > 1 && x < 10 || x == 0) // && before ||
	fmt.Println(x&1 == 1)                  // (x&1) == 1, unlike C
}
14
20
17
3
6
3
2
true
true

gofmt shows precedence with spacing. It removes spaces around higher-precedence operators, so 2 + 3*4 and 1 + 2<<3 make the grouping visible. When in doubt, add parentheses.

1 + 2<<3 is 17, not 24 like in C, where << binds looser than +. Be careful when porting bit manipulation code from C or Java.

No ternary operator

Go doesn't have cond ? a : b. The Go authors felt it was used to write hard-to-read expressions. Use an if statement, or the built-in min and max functions (Go 1.21+):

package main

import "fmt"

func main() {
	a, b := 5, 3

	// instead of: big := a > b ? a : b
	big := b
	if a > b {
		big = a
	}
	fmt.Println(big)

	// built-in min and max (Go 1.21+) work on any ordered type
	fmt.Println(max(a, b), min(a, b, -1), max(2.5, 1), min("go", "c"))

	// clamp a value to a range
	v := 150
	fmt.Println(min(max(v, 0), 100))
}
5
5 -1 2.5 c
100

No operator overloading

You can't define + or == for your own types. Types such as big.Int, time.Time and time.Duration use methods instead: x.Add(y, z), t1.Before(t2), t1.Equal(t2).

Operators do work on defined types whose underlying type supports them. time.Duration is an int64, so 2 * time.Second and d1 + d2 work, as do the Perm flags above.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents