Logical Operators
You can combine conditions with logical operators:
| Operator | Name | true when... |
|---|---|---|
&& | AND | both sides are true |
|| | OR | at least one side is true |
! | NOT | flips the value (true ↔ false) |
umur := 20
punyaSIM := true
if umur >= 17 && punyaSIM {
fmt.Println("Boleh menyetir")
}
hariLibur := false
if !hariLibur {
fmt.Println("Kantor buka")
}
The first if prints "Boleh menyetir" ("allowed to drive") when the person is at least 17 and has a driver's license; the second prints "Kantor buka" ("office is open") when it's not a holiday.
Short-circuit evaluation
Go stops checking as soon as the result is certain:
- in
a && b, ifais alreadyfalse,bis not evaluated; - in
a || b, ifais alreadytrue,bis not evaluated.
Returning a bool directly
A comparison expression already is a bool, so you don't need an if just to return true/false:
// bertele-tele
if saldo >= harga {
return true
}
return false
// ringkas
return saldo >= harga
The first version is long-winded; the second says the same thing in one line.
Task
The city library has two rules. Complete both functions:
-
bolehPinjam(umur int, punyaKartu bool, sedangDipinjam int) boolA member can borrow a book if all of these are true: they're at least12years old, they have a library card, and the number of books they currently have out is less than3. -
bebasDenda(hariTerlambat int, anggotaPremium bool) boolA return has no late fee if it isn't late (hariTerlambat <= 0) or the member is a premium member.