Data Types
Constants and Iota
Constants name values that do not change, and iota can count related constants.
iota
Inside a Go constant block, `iota` starts at zero and increases by one on each line.
Constants and Iota
constants_iota.go
Replay: real traced execution (multi-file project)
package main
import "fmt"
const (
StatusNew = iota
StatusActive
StatusDone
)
func main() {
var status = StatusActive
label := ""
if status == StatusNew {
label = "new"
} else if status == StatusActive {
label = "active"
} else {
label = "done"
}
fmt.Println("status=", status)
fmt.Println("label=", label)
}
package main
import "fmt"
const (
StatusNew = iota
StatusActive
StatusDone
)
func main() {
var status = StatusNew
label := ""
if status == StatusNew {
label = "new"
} else if status == StatusActive {
label = "active"
} else {
label = "done"
}
fmt.Println("status=", status)
fmt.Println("label=", label)
}
package main
import "fmt"
const (
StatusNew = iota
StatusActive
StatusDone
)
func main() {
var status = StatusDone
label := ""
if status == StatusNew {
label = "new"
} else if status == StatusActive {
label = "active"
} else {
label = "done"
}
fmt.Println("status=", status)
fmt.Println("label=", label)
}
status ← 1, StatusActive ← 1, label ← ""
11func main() {12 var status→ 1 = StatusActive→ 1 //@status=StatusNew, StatusDone13 label→ "" := ""label ← "active"
16 label = "new"17} else if status1 == StatusActive1 {18 label→ "active" = "active"19} else {fmt.Println("status=", status)
23 fmt.Println("status=", status1)24 fmt.Println("label=", label"active")25}outputstatus= 1 label= active
status ← 0, StatusNew ← 0, label ← ""
11func main() {12 var status→ 0 = StatusNew→ 013 label→ "" := ""label ← "new"
15if status0 == StatusNew0 {16 label→ "new" = "new"17} else if status == StatusActive {fmt.Println("status=", status)
23 fmt.Println("status=", status0)24 fmt.Println("label=", label"new")25}outputstatus= 0 label= new
status ← 2, StatusDone ← 2, label ← ""
11func main() {12 var status→ 2 = StatusDone→ 213 label→ "" := ""label ← "done"
18 label = "active"19} else {20 label→ "done" = "done"21}fmt.Println("status=", status)
23 fmt.Println("status=", status2)24 fmt.Println("label=", label"done")25}outputstatus= 2 label= done
Follow the Labels
StatusNewis0.StatusActiveis1.StatusDoneis2.statusstarts asStatusActive, so its number is1.- The matching label is
active, so the program printsstatus= 1andlabel= active. | status value | number | label | | --- | --- | --- | | StatusNew | 0 | new | | StatusActive | 1 | active | | StatusDone | 2 | done |
Exercise: constants_iota.go
Reproduce label= active, then use the pinned status values StatusNew and StatusDone to predict each label.