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:
- A new named type, so the enum can't be mixed up with a plain
int. - A
constblock. - 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.
Ukuran(size:Kecil,Sedang,Besar, that is small, medium, large) must start at 1; skip the value 0 with_.Topping(Gula,Susu,Krim, that is sugar, milk, cream) must be bit flags using1 << 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