乐闻世界logo
搜索文章和话题

How do you create a loop in Go?

1个答案

1

In Go, there are three primary ways to implement loops: for loops, while loops (implemented using for in Go), and range loops.

1. for Loop

for loops are the most commonly used loop structure in Go, with the basic syntax as follows:

go
for initialization statement; condition expression; post-processing statement { // loop body }

Example:

go
for i := 0; i < 10; i++ { fmt.Println(i) }

In this example, the loop prints numbers from 0 to 9.

2. while Loop

In Go, while loops can be implemented using for loops by omitting the initialization and post-processing statements.

Example:

go
i := 0 for i < 10 { fmt.Println(i) i++ }

This example simulates a traditional while loop, printing numbers from 0 to 9.

3. range Loop

range loops are used to iterate over arrays, slices, strings, maps, or channels. range returns two values: the index of the element and the element itself.

Example:

go
nums := []int{1, 2, 3, 4, 5} for index, value := range nums { fmt.Printf("index: %d, value: %d\n", index, value) }

This example iterates over an integer slice and prints the index and value of each element.

These are the three primary methods for implementing loops in Go. Depending on your specific needs, you can choose the most suitable method to implement loop logic.

2024年7月20日 03:20 回复

你的答案