iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Operators

Go operators: arithmetic, comparison, logical, bitwise, pointer, and the type rules that surprise newcomers.

Go — operators

EXAMPLE
// ===== Arithmetic =====
a + b
a - b
a * b
a / b      // integer division when both are integers; 7 / 2 == 3
a % b      // modulo
-a

// Integer overflow WRAPS silently in Go:
var i int8 = 127
i++        // -128

// ===== Comparison =====
a == b
a != b
a < b
a > b
a <= b
a >= b

// Strings compare byte-wise. Use 'strings' package for case-insensitive etc.

// ===== Logical =====
&&  ||  !

// Short-circuit: a && b does NOT evaluate b if a is false.

// ===== Bitwise =====
a & b      // AND
a | b      // OR
a ^ b      // XOR
a &^ b     // AND NOT (clear bits) — Go-specific
a << n     // shift left
a >> n     // shift right

// ===== Assignment + compound =====
a = b
a += b
a -= b
a *= b
a /= b
a %= b
a |= b
a &= b
a ^= b
a &^= b
a <<= n
a >>= n

// ===== Increment + decrement (statements, not expressions!) =====
i++
i--
// j := i++   // ERROR: i++ is a statement, not an expression

// ===== Address-of + dereference =====
x := 42
p := &x       // p is *int
*p = 99       // x is now 99

// ===== Channels =====
ch <- 5       // send
v := <-ch     // receive
v, ok := <-ch // receive with ok = false on closed empty channel

// ===== Type rules =====
// Go does NOT auto-convert between numeric types:
var i int = 5
var f float64 = float64(i) + 0.5    // explicit conversion required

// Comparing different numeric types is a compile error:
//   var x int = 5
//   var y int64 = 5
//   x == y       // ERROR: mismatched types

// String + string is concatenation; no + with byte slices:
s := "hello" + " world"
// b := []byte("a") + []byte("b")    // ERROR

// ===== Precedence (high to low) =====
// 5: unary (!, -, ^, *, &)
// 4: *, /, %, <<, >>, &, &^
// 3: +, -, |, ^
// 2: ==, !=, <, <=, >, >=
// 1: &&
// 0: ||

// When in doubt, parenthesise.

// ===== Patterns to internalise =====
// - Explicit conversions; Go is picky about numeric types
// - Integer division truncates; cast to float when needed
// - i++ / i-- are STATEMENTS — no value
// - Channel ops with ok form for safe receive

// ===== Pitfalls =====
// - Integer overflow wraps silently
// - 5 / 2 == 2 (integer division)
// - Comparing different numeric types -> compile error
// - Shift by negative or oversized amount -> runtime panic / undefined

Why it matters

Go operators look familiar but the rules are strict: explicit numeric conversions, integer division truncates, ++ is a statement, no auto-coerce. Reach for the conversion functions and parenthesise when precedence matters. The strictness pays back in code that does what it says.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
a, b := 7, 3
fmt.Println(a+b, a-b, a*b, a/b, a%b)
Try it Yourself »

Discussion

Loading…