ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)
Set your Publisher ID in src/config/ads.ts to display live ads.
Go (Golang) Tutorial• 6 min read
Control Flow: if with short statements & The Universal for Loop
Why Go has only ONE loop keyword (for) and modern switch cases
Go simplifies syntax by providing only ONE looping keyword: for. It can be used as a traditional loop, a while loop, or an infinite loop.
The Universal for Loop & If Scoping
Standard for: for i := 0; i < 5; i++ { ... }.
While loop equivalent: for condition { ... }.
Infinite loop: for { ... }.
If with short statement: if err := doWork(); err != nil { ... } scopes err strictly to the if/else block.
Control Flow in Go
package main
import "fmt"
func main() {
// If with short statement initialization
if score := 85; score >= 80 {
fmt.Println("Passed with honors:", score)
}
// Range-based for loop over slice
items := []string{"Go", "Rust", "TypeScript"}
for index, val := range items {
fmt.Printf("Index %d: %s\n", index, val)
}
}ADVERTISEMENT
Google AdSense Slot (inContentBanner)
Set your Publisher ID in src/config/ads.ts to display live ads.
Test Yourself With Exercise
How many different looping keywords (e.g. while, do-while, for) exist in the Go language specification?