Go Reference ยท Operators
Go arithmetic operators
Reference for Go arithmetic operators + - * / %: integer versus float division, remainder sign, overflow wrapping, division by zero and constant arithmetic.
Go has five binary arithmetic operators, +, -, *, / and %, plus unary + and -, and the statements x++ and x--. The operands of a binary operator must have the same type: Go never converts between numeric types implicitly, so int + int64 does not compile.
+ also concatenates strings. % works only on integers. Division of two integers truncates toward zero, while division of floats is exact to the type's precision.
fmt.Println(7/2, 7%2, -7/2, -7%2) // 3 1 -3 -1
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
x + y x - y x * y x / y x % y +x -x x++ x-- // statements, not expressions x += y x %= y // compound assignment
| Operator | Operands | Result |
|---|---|---|
+ |
integers, floats, complex, strings | sum, or concatenation for strings |
-, * |
integers, floats, complex | difference, product |
/ |
integers, floats, complex | quotient; integers truncate toward zero |
% |
integers only | remainder with the sign of the dividend; x == (x/y)*y + x%y |
Errors and edge cases: integer division or remainder by zero panics (or is a compile error for a constant zero divisor). Float division by zero gives +Inf, -Inf or NaN. The most negative integer divided by -1 overflows and yields the same value without a panic.
Usage notes
- Integer overflow wraps silently using two's complement for both signed and unsigned types. Check ranges yourself, or use
math/bits(Add64,Mul64) ormath/bigfor exact results. - Remainder sign. In Go
-7 % 3is-1, not2. For a modular result in0..m-1use((x % m) + m) % m. - Mixed types. Convert explicitly (
float64(n) / 2). Untyped constants adapt:x * 2works for any numericx. - Constants are exact. Constant expressions are evaluated with arbitrary precision and only rounded when assigned to a typed variable, so
1<<100 / 1<<98is4as above. - Floating-point rounding.
0.1 + 0.2 != 0.3. Compare floats with a tolerance and use integers (cents) for money. ++and--are statements and exist only in postfix form;y = x++does not compile.- Strings.
s += tin a loop is quadratic; see strings.Builder. - Complex numbers support
+ - * /but not%.