Chapter 3 of 20
Operators
Arithmetic / comparison / logic / bitwise / assignment
Arithmetic Operators
- + - * / : the usual four operations
- % : remainder (integers only)
- ++ / -- : increment/decrement — statements only, not expressions
package main
import "fmt"
func main() {
a, b := 7, 3
fmt.Println(a/b) // 2 (integer division)
fmt.Println(a%b) // 1
a++ // valid
fmt.Println(a)
// fmt.Println(a++) // compile error: a++ is not an expression
}Comparison and Logic
== != < <= > >= return a bool; the logical operators && || ! use short-circuit evaluation.
package main
import "fmt"
func main() {
age, name := 20, "Alice"
ok := age >= 18 && name != ""
if !ok {
fmt.Println("invalid")
return
}
fmt.Println("ok:", name)
}Bitwise Operations
- & bitwise AND, | bitwise OR, ^ XOR
- &^ bit clear (AND NOT)
- << left shift, >> right shift
package main
import "fmt"
func main() {
flags := 0b1010
fmt.Printf("%04b\n", flags|0b0101) // 1111
fmt.Printf("%04b\n", flags&^0b0010) // 1000
fmt.Printf("%04b\n", flags<<1) // 10100
}Compound Assignment
package main
import "fmt"
func main() {
x := 10
x += 5 // 15
x *= 2 // 30
x >>= 1 // 15
fmt.Println(x)
}Operator Precedence
Go's precedence is simpler than C's: unary > multiplication-division/bitwise > addition-subtraction/bitwise > comparison > && > ||. Use parentheses liberally so readers don't have to consult a table.