पाठ 5 / 26
Control Flow
if, for, switch.
One loop, flexible switch
Go has a single loop keyword, for, used as a classic three-part loop, a while-style loop (for cond {}), an infinite loop (for {}), and with range over slices, maps, strings, channels, and integers (for i := range 5). if can include a short statement (if err := f(); err != nil). switch needs no break, cases can be expressions, and a switch with no value works like a chain of if/else.
Loops and a value-less switch, run
I ran this with Go 1.27.1 (go run . in a module named demo, standard library only). A counting loop, a while-style loop halving n, and a range loop calling a switch-based grade function.
package main
import "fmt"
func grade(score int) string {
switch {
case score >= 90:
return "A"
case score >= 75:
return "B"
default:
return "C"
}
}
func main() {
for i := 1; i <= 3; i++ { // the only loop keyword is for
fmt.Print(i, " ")
}
fmt.Println()
n := 10
for n > 1 { // "while" style
n /= 2
}
fmt.Println("n =", n)
for _, s := range []int{95, 80, 60} {
fmt.Print(grade(s), " ")
}
fmt.Println()
}
Output:
1 2 3 n = 1 A B C
Use if with a short statement
if v, err := f(); err != nil { ... } keeps variables scoped to where they are needed.
त्वरित जाँच: How do you write a while loop in Go?
- while condition { ... }
- for condition { ... }
- do { } while
- loop until condition
Answer
for condition { ... } — for covers every loop form.