Go course

ConditionalsLogical Operators

Go

Display

Theme

Conditionals · Test exercise

Logical Operators

You can combine conditions with logical operators:

OperatorNametrue when...
&&ANDboth sides are true
||ORat least one side is true
!NOTflips 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, if a is already false, b is not evaluated;
  • in a || b, if a is already true, b is 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:

  1. bolehPinjam(umur int, punyaKartu bool, sedangDipinjam int) bool A member can borrow a book if all of these are true: they're at least 12 years old, they have a library card, and the number of books they currently have out is less than 3.

  2. bebasDenda(hariTerlambat int, anggotaPremium bool) bool A return has no late fee if it isn't late (hariTerlambat <= 0) or the member is a premium member.

main.go
package main

import "fmt"

func bolehPinjam(umur int, punyaKartu bool, sedangDipinjam int) bool {
	// TODO: gabungkan ketiga syarat dengan &&
	return false
}

func bebasDenda(hariTerlambat int, anggotaPremium bool) bool {
	// TODO: gunakan ||
	return false
}

func main() {
	fmt.Println(bolehPinjam(15, true, 1))
	fmt.Println(bebasDenda(4, true))
}

Output

Go runtime not loaded yet

Press Run to see the output, or Submit to check your code.

Ctrl/Cmd + Enter: Run · Ctrl/Cmd + Shift + Enter: Submit · Ctrl/Cmd + S: tidy the code (gofmt)