Operators
Go's operators look familiar from almost any C-family language, but Go is far stricter about mixing types than most of them — nothing gets silently converted for you.
Arithmetic operators
package main import "fmt" func main() { a, b := 17, 5 fmt.Println(a + b) fmt.Println(a - b) fmt.Println(a * b) fmt.Println(a / b) fmt.Println(a % b) }
22 12 85 3 2
a, b := 17, 5 declares two variables in one line, both inferred as int. a / b prints 3, not 3.4 — dividing two integers in Go always produces an integer result, truncating any remainder, which a % b then recovers.
int and float64. Writing 17 / 5.0 with a mix of an int variable and a float64 literal is a compile error; you have to convert explicitly with float64(a) / 5.0. This is more strict than C, C++, C#, or Java, all of which will happily promote an int to a floating-point type for you.Comparison and logical operators
package main import "fmt" func main() { age := 20 hasTicket := true fmt.Println(age >= 18) fmt.Println(age >= 18 && hasTicket) fmt.Println(age < 18 || !hasTicket) }
true true false
>=, <, and friends all return a plain bool. && (and) and || (or) short-circuit exactly like in C, C++, JavaScript, and most other languages here — the right side of && is never evaluated if the left side is already false.
Explicit type conversion
package main import "fmt" func main() { total := 17 count := 5 average := float64(total) / float64(count) fmt.Println(average) }
3.4
float64(total) converts total's value to a float64 without changing what total itself is — the conversion produces a new value, and division between two float64s does the real division you'd expect.