Master Go’s for loop - the only loop construct you need. Learn basic loops, break, continue, nested loops, for-range, labels, and goto
Go has only one looping construct: the for loop. However, it’s flexible enough to handle all looping scenarios. There’s no while or do-while in Go - the for loop does it all.
Use continue to skip the rest of the current iteration:
var ( sum int i = 1)for { if i > 10 { break } i++ // Increment BEFORE continue if i%2 != 0 { continue // Skip odd numbers } sum += i fmt.Println(i, "-->", sum)}fmt.Println(sum) // Sum of even numbers 2-10
Be careful with continue! Make sure to increment your counter before the continue statement, or you’ll create an infinite loop:
// WRONG - Infinite loop!for { if i%2 != 0 { continue // i never increments! } i++}// CORRECTfor { i++ if i%2 != 0 { continue } // rest of code}
// Method 1: Traditional for loopfor i := 1; i < len(os.Args); i++ { fmt.Printf("%q\n", os.Args[i])}// Method 2: Range with skip first elementfor i, v := range os.Args { if i == 0 { continue // Skip program name } fmt.Printf("%q\n", v)}// Method 3: Range with slice (BEST)for _, v := range os.Args[1:] { fmt.Printf("%q\n", v)}
Method 3 is the most idiomatic - use slice syntax [1:] to skip the first element.
const corpus = "lazy cat jumps again and again and again"words := strings.Fields(corpus)query := os.Args[1:]queries: for _, q := range query { for i, w := range words { if q == w { fmt.Printf("#%-2d: %q\n", i+1, w) break queries // Break the outer loop } } }
Without the label, break would only exit the inner loop.
queries: // Label scope is the entire function for _, q := range query { for i, w := range words { if q == w { break queries // Can reference label from anywhere in function } } }
// Less efficient - calls len() every iterationfor i := 0; i < len(items); i++ { process(items[i])}// More efficient - cache lengthn := len(items)for i := 0; i < n; i++ { process(items[i])}// Most idiomatic - use rangefor _, item := range items { process(item)}