Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for For, Four Ways: Mastering Loops in Go
Quinterabok
Quinterabok

Posted on

     

For, Four Ways: Mastering Loops in Go

Go's elegance lies in its simplicity. While other languages offer multiple looping constructs (while, do-while, for, etc.), Go streamlines everything into a single, versatile keyword: for. Don't let this simplicity fool you—Go's for loop is remarkably flexible and powerful. Let's explore four essential ways to harness its capabilities.

1. The Classic For Loop

The traditional C-style for loop consists of three components: initialization, condition, and post-statement. This is perfect when you need precise control over your iteration:

funcmain(){// Print numbers from 1 to 5fori:=1;i<=5;i++{fmt.Println(i)}}
Enter fullscreen modeExit fullscreen mode

Here's what each component does:

i := 1 - Initializes the counter
i <= 5 - Defines the continuing condition
i++ - Executes after each iteration

2. The While-Style Loop

Need a while loop? In Go, it's just a for loop with a condition. Simply omit the initialization and post statements:

funcmain(){for{fmt.Println("Forever and ever...")time.Sleep(time.Second)// Use 'break' to exit when neededifsomeCondition{break}}}
Enter fullscreen modeExit fullscreen mode

This pattern is common in server programs, event listeners, and game loops.

3. The Infinite Loop

Sometimes you need a loop that runs indefinitely (until broken). Go makes this remarkably clean:

funcmain(){for{fmt.Println("Forever and ever...")time.Sleep(time.Second)// Use 'break' to exit when neededifsomeCondition{break}}}
Enter fullscreen modeExit fullscreen mode

This pattern is common in server programs, event listeners, and game loops.

4. Range-Based Loop

The range keyword is your best friend when working with collections. It provides a clean way to iterate over arrays, slices, maps, strings, and channels:

// Iterating over a slicenumbers:=[]int{1,2,3,4,5}forindex,value:=rangenumbers{fmt.Printf("Index: %d, Value: %d\n",index,value)}// Iterating over a mapages:=map[string]int{"Alice":25,"Bob":30,"Carol":35,}forname,age:=rangeages{fmt.Printf("%s is %d years old\n",name,age)}
Enter fullscreen modeExit fullscreen mode

The range form automatically handles the details of iteration, making your code more readable and less prone to errors.

Best Practices and Tips

1.Choose the Right Form:

Select the loop style that best fits your use case. Don't use a classic for loop when range would be clearer.

2.Break and Continue:

Remember you can use break to exit a loop early and continue to skip to the next iteration:

fori:=1;i<=10;i++{ifi%2==0{continue// Skip even numbers}ifi>7{break// Stop after 7}fmt.Println(i)}
Enter fullscreen modeExit fullscreen mode

3. Label Your Loops:

When working with nested loops, labels can help control which loop to break or continue:

outer:fori:=0;i<3;i++{forj:=0;j<3;j++{ifi*j>4{breakouter}fmt.Printf("i=%d, j=%d\n",i,j)}}
Enter fullscreen modeExit fullscreen mode

Conclusion

Go's for loop might seem basic at first glance, but its flexibility makes it a powerful tool in your programming arsenal. By mastering these four patterns, you'll be able to handle any iteration need that comes your way, from simple counting to complex data structure traversal.

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Go|Python|Rust|JavaScript|Django |Software Developer at Zone01Kisumu
  • Location
    Kenya
  • Joined

More fromQuinterabok

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp