Go🔧Core Languagebeginner
Control Flow
Go · Core Language · Run with go run
Explanation
Go has `if`, `for`, and `switch` — no `while`, no `do-while`, no `until`. `for` covers all looping: classic C-style, while-style, and range-based. `switch` does not fall through by default (no `break` needed); use `fallthrough` explicitly when required.
Real-World Scenario
`for range` over a channel is the standard way to consume a stream of results from a concurrent worker, blocking until the channel is closed.
Quick Snippet
snippet.go
// if with initialization statement
if err := doWork(); err != nil {
log.Fatal(err)
}
// for as while
for running {
process()
}
// range over slice (index, value)
for i, v := range items {
fmt.Println(i, v)
}
// switch — no fall-through by default
switch status {
case 200: fmt.Println("OK")
case 404: fmt.Println("Not Found")
default: fmt.Println("Other")
}Full Example
control_flow.go
// Compile: go run control_flow.go
// Output:
// err check: ok
// countdown: 3 2 1
// even: 0 2 4
// status 200: OK
package main
import "fmt"
func doWork() error { return nil }
func main() {
// if with initialization statement
if err := doWork(); err != nil {
fmt.Println("error:", err)
} else {
fmt.Println("err check: ok")
}
// for as while
n := 3
fmt.Print("countdown:")
for n > 0 {
fmt.Print(" ", n)
n--
}
fmt.Println()
// range over slice
fmt.Print("even:")
for _, v := range []int{0, 1, 2, 3, 4} {
if v%2 != 0 {
continue
}
fmt.Print(" ", v)
}
fmt.Println()
// switch — no fall-through by default
status := 200
switch status {
case 200:
fmt.Println("status 200: OK")
case 404:
fmt.Println("status 404: Not Found")
default:
fmt.Println("status: Other")
}
}
Run command
go run control_flow.go