Module lessons (4/5)
Operators
Go-style algebra, logic, and bitmask
Use arithmetic, logical and bitwise operators respecting the anti-ambiguity rules of the compiler.
Go offers clear and predictable operators, purposely dispensing with the ternary operator (a ? b : c), operator overloading, and implicit cross-type promotions.
Arithmetic operators and integer division
package main
import "fmt"
func main() {
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: tronca la parte decimale)
fmt.Println(a % b) // 1 (resto della divisione)
}++ and -- are statements, not expressions
Unlike C or JavaScript, in Go x++ and x-- exist only in suffixed form as self-contained statements: they do not return any values.
package main
import "fmt"
func main() {
count := 5
count++ // valido: istruzione isolata
// next := count++ // ERRORE di compilazione
fmt.Println(count)
}Logic comparison and short circuit
The relational operators (==, !=, <, <=, >, >=) produce bool, while &&, || and ! evaluate from left to right, stopping as soon as the result is certain:
package main
import "fmt"
type Account struct{ Active bool }
func main() {
age := 24
inRange := age >= 18 && age <= 65
var acc *Account = nil
// Sicuro: acc != nil e' false, quindi acc.Active non viene valutato
canLogin := acc != nil && acc.Active
fmt.Println("abc" < "abd", inRange, canLogin)
}Bitwise and AND NOT (&^)
In addition to the classic &, |, ^, << and >>, Go includes &^ (bit clear): it clears the bits that are 1 in the right mask, without the need for the inversion ^mask:
package main
import "fmt"
func main() {
flags := uint8(0b0000_0011)
flags |= 0b0000_0100 // accende il bit 2 -> 0000_0111
flags &^= 0b0000_0010 // spegne il bit 1 -> 0000_0101
hasWrite := flags&0b0000_0100 != 0
fmt.Printf("%08b %t\n", flags, hasWrite)
}Guided practice
Calculate the remainder of the integer division of 17 by 5 in remainder and print it. Expected: 2.
Show hint
Use the modulus operator %: remainder := 17 % 5.
Solution available after 3 attempts
Set the boolean adult to true if age is between 18 and 65 inclusive, then print it.
Show hint
Join the two threshold conditions with &&: age >= 18 && age <= 65.
Solution available after 3 attempts
Starting at perms := uint8(0b0011), turn on the 0b0100 bit with |= and turn off the 0b0001 bit with &^=, then print perms in binary.
Show hint
perms |= 0b0100 turns on the third bit and perms &^= 0b0001 turns off the first bit.
Solution available after 3 attempts
Check for understanding
What does this code print?
a, b := 7, 2
fmt.Println(a/b, a%b)Why does y := x++ generate a compilation error in Go?
x := 5
y := x++