Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 147 ยท Operators and Control Flow

Operators

Learn every Go operator - arithmetic, comparison, logical with short-circuiting, bitwise (including &^), assignment operators, ++ and --, precedence, and why there is no ternary.

Operators are the symbols that combine values: + adds, == compares, && joins two conditions. Go has the operators you know from other C-family languages, but with a few deliberate differences: there is no ternary ?:, ++ and -- are statements instead of expressions, operands must have exactly the same type, and there are only five precedence levels to remember.

This lesson walks through every group of operators, shows what each one does on real values, and points out the traps (integer division, overflow, mixing types). Everything here builds on the basic types and type conversion lessons, and the next lesson, if, else if and else, puts comparison and logical operators to work.

Arithmetic operators

The arithmetic operators work on numbers; + also joins strings.

Operator Meaning Works on
+ addition, string concatenation numbers, strings
- subtraction, negation numbers
* multiplication numbers
/ division numbers
% remainder integers only

Division on integers truncates toward zero: the fractional part is thrown away, and the result for negative numbers is the one closer to zero. The remainder has the sign of the left operand, so a == (a/b)*b + a%b always holds.

Go Arithmetic on integers, floats and strings

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.

The line fmt.Println(7/2, 7/2.0) prints 3 3.5. Both operands of 7/2 are untyped integer constants, so the division is integer division. In 7/2.0 the constant 2.0 is a float, so the compiler converts the whole expression to floating point. This only applies to constants. With variables, the types are fixed, as the next section shows.

Dividing an integer by zero is a runtime panic (panic: runtime error: integer divide by zero), and the compiler rejects a constant divisor of zero. Floating-point division by zero does not panic: it produces +Inf, -Inf or NaN. See Numbers and Math for details.

Both operands must have the same type

Go never converts between numeric types implicitly. An int and a float64 cannot be added, and neither can an int and an int64. This looks strict, but it removes a whole class of surprises that other languages have (silent truncation, sign changes, lost precision).

Go Mixing int and float64 (fails on purpose)

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.

The compiler stops with an error like this:

TEXT
./main.go:8:11: invalid operation: count * price (mismatched types int and float64)

Convert one side explicitly and say what you mean:

Go Explicit conversion fixes the mismatch

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.

The result is 7.5 followed by 7 (because 2.5 * 3 is 7.5, and int truncates).

Comparison operators

Comparisons produce an untyped boolean: ==, !=, <, <=, >, >=. Both operands must have the same type again. Strings compare byte by byte (so "Z" < "a", because uppercase letters come first in ASCII and UTF-8).

== and != work on any comparable type: numbers, strings, booleans, pointers, channels, arrays and structs whose fields are all comparable, and interface values. Slices, maps and functions are not comparable with == (you can only compare them to nil); use slices.Equal or maps.Equal for contents.

Go Comparing values

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.

Logical operators and short-circuiting

&& (and), || (or) and ! (not) work on booleans only. Go has no "truthy" values: if count { is a compile error when count is an int; you must write if count != 0 {.

&& and || short-circuit: the right operand is evaluated only if the left one does not already decide the result. That makes guards like i < len(items) && items[i] == x safe, because the index is only used when it is in range.

Go Short-circuit evaluation

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.

Function B and function D never run. The output shows only evaluating A, evaluating C and evaluating E, each followed by the result of its expression.

Bitwise operators

Bitwise operators work on the individual bits of integers.

Operator Meaning
& AND
| OR
^ XOR (binary), NOT (unary: ^x flips every bit)
&^ AND NOT, also called "bit clear"
<< shift left
>> shift right

Go's &^ is unusual. a &^ b clears the bits of a that are set in b, so it is the idiomatic way to remove a flag. There is no ~ operator: unary ^ does that job.

Shifts fill with zeros on the left for unsigned types and with the sign bit for signed types (an arithmetic shift). Shifting by the type's width or more gives 0 (or -1 for a negative signed value shifted right). The shift count can be any integer type, but a negative count panics at run time.

Go Bit flags with &, |, ^ and &^

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.

The constants use iota, which the Constants and iota lesson explains. The %04b verb prints a number in binary padded to four digits; Printing with fmt lists all the verbs.

Assignment operators, ++ and --

Every binary arithmetic and bitwise operator has an assignment form: +=, -=, *=, /=, %=, &=, |=, ^=, &^=, <<= and >>=. x += 3 means x = x + 3, with x evaluated once.

x++ and x-- add or subtract one, but they are statements, not expressions. There is no prefix form (++x is a syntax error), and you cannot use them inside another expression. This removes the confusing a[i++] = i++ puzzles that C programmers know.

Go Compound assignment, and integer overflow

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.

The total calculation goes 15, 30, 26, 13, and 13 % 7 is 6. The two overflow lines print -128 and 255: Go integers use two's complement wraparound and do not report overflow at run time. A constant that does not fit is a compile error (var b int8 = 128 is rejected), but arithmetic on variables silently wraps. If you need overflow detection, check ranges yourself or use math/big (see Numbers and Math).

Because ++ is a statement, this does not compile:

Go ++ is not an expression (fails on purpose)

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.

The compiler reports:

TEXT
./main.go:7:8: syntax error: unexpected ++ at end of statement

Operator precedence

When an expression has several operators, precedence decides the grouping. Go has just five levels (higher binds tighter):

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

Unary operators (!, -, ^, *, &, <-) bind tighter than any binary operator. Two things differ from C: & and the shifts sit at the same level as * (so a & b + c means (a & b) + c... which is surprising only if you expect C's rules), and comparisons rank below the arithmetic and bitwise operators, so x & mask == 0 is parsed as x & (mask == 0)... no wait: == is lower, so it is (x & mask) == 0, which is what you want.

Go Precedence in action

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.

When in doubt, add parentheses. gofmt also helps: it spaces the operators according to their precedence, so 1 + 2<<3 visibly groups the shift first.

Why there is no ternary operator

Go has no cond ? a : b. The language designers found that it is too easy to write unreadable nested conditionals with it, and an ordinary if is clear enough. Assign the value inside an if/else, or wrap it in a small function:

Go Replacing the ternary operator

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.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does fmt.Println(-7 / 2, -7 % 2) print?

    Integer division truncates toward zero, so -7 / 2 is -3. The remainder takes the sign of the left operand, so -7 % 2 is -1.
  2. 2. Given a := 5 and b := 2.0, why does a * b fail to compile?

    Both operands must have the same type. Write float64(a) * b, or int(b) * a if you really want integers.
  3. 3. In if i < len(items) && items[i] > 0 {, what happens when i equals len(items)?

    && short-circuits: when the left side is false, the right side is skipped, so the out-of-range index is never used.
  4. 4. What is the value of x after x := 0b1111; x &^= 0b0101?

    &^ clears the bits that are set in the right operand. Clearing bits 0 and 2 of 1111 leaves 1010.
  5. 5. Which statement about y := x++ is true?

    In Go, ++ and -- are statements. They cannot be used inside another expression or assignment.

Summary

  • Arithmetic operators are + - * / %; integer division truncates toward zero and % takes the sign of the left operand.
  • Both operands must have the same type. Convert explicitly with float64(x) or int(y); untyped constants adapt to the other operand.
  • Comparisons work on comparable types (including arrays and structs); slices, maps and functions only compare to nil.
  • && and || short-circuit and accept booleans only; there are no truthy or falsy values.
  • Bitwise operators are & | ^ &^ << >>; unary ^ flips bits and &^ clears them.
  • x += y style assignment operators exist for every binary operator; x++ and x-- are statements.
  • Integer overflow wraps around silently at run time, but out-of-range constants are compile errors.
  • There are five precedence levels, there is no ternary operator, and min/max built-ins (Go 1.21) cover many simple cases.

Next: if, else if and else