Go course

EnumsEnums with const and iota

Go

Display

Theme

Enums · Output exercise

Enums with const and iota

Many languages have an enum keyword for defining a set of named values, like the days of the week or the status of an order. Go has no enum keyword. Instead, Go combines three things you already know:

  1. A new named type, so the enum can't be mixed up with a plain int.
  2. A const block.
  3. The automatic counter iota.
type Musim int

const (
	Kemarau Musim = iota // 0
	Hujan                // 1
)

How iota works

Inside a const block, iota is 0 on the first line and goes up by one on every line. If a line doesn't write an expression, Go repeats the previous line's expression, type included. That's why you only need to write = iota once.

type Hari int

const (
	Senin Hari = iota // 0
	Selasa            // 1
	Rabu              // 2
)

The named type Hari means the compiler rejects mistakes like mixing Hari with another enum type without a conversion.

Skipping values

Use the blank identifier _ to "throw away" an iota value. A common pattern is to skip 0 so the zero value isn't accidentally treated as a valid choice.

const (
	_      Prioritas = iota // 0 dibuang
	Rendah                  // 1
	Sedang                  // 2
	Tinggi                  // 3
)

Expressions with iota: bit flags

You can use iota inside an expression. With the bit shift 1 << iota, each constant gets its own bit, so several options can be combined with |:

type Fitur int

const (
	FiturA Fitur = 1 << iota // 1  (biner 001)
	FiturB                   // 2  (biner 010)
	FiturC                   // 4  (biner 100)
)

aktif := FiturA | FiturC // 5
punyaC := aktif&FiturC != 0 // true

Task

A coffee shop has two enums in the editor.

  1. Ukuran (size: Kecil, Sedang, Besar, that is small, medium, large) must start at 1; skip the value 0 with _.
  2. Topping (Gula, Susu, Krim, that is sugar, milk, cream) must be bit flags using 1 << iota.

The printing code in main is already there; don't change it. Expected output:

Kecil: 1
Sedang: 2
Besar: 3
Gula: 1
Susu: 2
Krim: 4
Gula+Krim: 5
Pakai susu? false
main.go
package main

import "fmt"

type Ukuran int

// TODO: mulai dari 1 (lewati 0 dengan _)
const (
	Kecil Ukuran = iota
	Sedang
	Besar
)

type Topping int

// TODO: jadikan bit flag dengan 1 << iota
const (
	Gula Topping = iota
	Susu
	Krim
)

func main() {
	fmt.Println("Kecil:", int(Kecil))
	fmt.Println("Sedang:", int(Sedang))
	fmt.Println("Besar:", int(Besar))

	fmt.Println("Gula:", int(Gula))
	fmt.Println("Susu:", int(Susu))
	fmt.Println("Krim:", int(Krim))

	pesanan := Gula | Krim
	fmt.Println("Gula+Krim:", int(pesanan))
	fmt.Println("Pakai susu?", pesanan&Susu != 0)
}

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)