Module lessons (4/5)
Operators
Go has the classic operators you'd expect, with few surprises:
arithmetic, comparison, logical, bitwise. No ternary operator
(a ? b : c), no overloading, no implicit conversions between types.
Simplicity is a feature.
Arithmetic
a, b := 10, 3
fmt.Println(a + b) // 13
fmt.Println(a - b) // 7
fmt.Println(a * b) // 30
fmt.Println(a / b) // 3 ← divisione INTERA tra interi
fmt.Println(a % b) // 1 ← resto (modulo)Increment and decrement are STATEMENTS, not expressions
x++ and x-- don't produce a value: they are "actions" and nothing
more. No y := x++ like in C.
x := 5
x++ // ok: incrementa x
// y := x++ // ERRORE di compilazione
fmt.Println(x) // 6Comparison
== != < <= > >= return bool. They apply to numbers and strings; for
structs ALL fields must be comparable (no slices/maps inside).
"abc" == "abc" // true
"abc" < "abd" // true (ordine lessicografico)
3 != 4 // trueLogical with short-circuit
&&, ||, !. They short-circuit from left to right: if the first
operand is enough to determine the result, the second is not even
evaluated.
adult := age >= 18
seniorAdult := age >= 18 && age < 65Bitwise
& AND, | OR, ^ XOR, << left shift, >> right shift, &^ AND
NOT (bit clear). They are useful for flags, binary parsing and
optimizations:
flags := uint8(0b0000_0011)
flags |= 0b0000_0100 // imposta un bit: 0000_0111
flags &^= 0b0000_0010 // cancella un bit: 0000_0101
hasFlag := flags & 0b0000_0100 != 0 // trueNo implicit conversions
1 + 1.5 in Go compiles, because both are untyped literals.
But var i int = 1; i + 1.5 does NOT: you need float64(i) + 1.5.
i := 1
f := 1.5
// i + f // ERRORE
float64(i) + f // 2.5Your turn
Compute in remainder the remainder of dividing 17 by 5 and print it. Expected: 2.
Show hint
The modulo operator is `%`.
Solution available after 3 attempts
Print true if age is between 18 and 65 inclusive, false otherwise.
Show hint
Combine two comparisons with `&&`.
Solution available after 3 attempts
What does this code print?
a, b := 7, 2
fmt.Println(a/b, a%b)Recap
- Classic arithmetic;
/between ints is integer division (truncates). ++and--are statements, not expressions: noy := x++.- Comparison and logical operators produce
bool;&&/||short-circuit. - Bitwise
& | ^ << >> &^for flags and binary parsing. - No implicit conversions between different types: use
type(x).