Loop Structures in Go

时尚2025-05-24阅读  28+

Loop Structures in Go

Go (Golang) provides several loop structures to handle different iteration scenarios. The primary loop structure in Go is the for loop, which is versatile and can be used in various forms to mimic other loop types. Below is an overview of loop structures in Go, along with examples.

1. Basic for Loop

The basic for loop in Go is to the for loop in other C-style languages. It consists of an initialization, a condition, and a post-statement, all separated by semicolons.

Syntax:

go

for initialization; condition; post-statement {

// Code to be executed in each iteration

}

Example:

go

package main

import "fmt"

func main() {

for i := 0; i < 5; i++ {

fmt.Printf("Iteration: %d\n", i)

}

}

This loop initializes i to 0, checks if i is less than 5, and increments i by 1 after each iteration. It prints the iteration number until i reaches 5.

2. for Loop Without Conditions (Infinite Loop)

If you omit the condition in a for loop, it becomes an infinite loop. You can break out of it using a break statement or a return statement.

Syntax:

go

for {

// Code to be executed indefinitely until a break or return

}

Example:

go

package main

import (

"fmt"

"time"

func main() {

count := 0

for {

fmt.Printf("Count: %d\n", count)

本站所有文章、数据、图片均来自互联网,一切版权均归源网站或源作者所有。文内含有的对外跳转链接(包括不限于超链接、二维码、口令等形式),用于传递更多信息,结果仅供参考,今日霍州所有文章均包含本声明。

猜你喜欢