loop list golang
Looping through a list in Go (Golang)
To loop through a list in Go (Golang), you can use the for
loop. Here's an example of how to loop through a list:
package main
import "fmt"
func main() {
list := []string{"apple", "banana", "cherry"}
for index, item := range list {
fmt.Println(index, item)
}
}
In this example, we have a list of strings list
containing three elements. We use the range
keyword to iterate over the list. The range
keyword returns both the index and the value of each element in the list. We assign the index to the variable index
and the value to the variable item
. Inside the loop, we can perform any desired operations using the index and item values.
The output of the above code will be:
0 apple
1 banana
2 cherry
This demonstrates how to loop through a list in Go (Golang) using the for
loop and the range
keyword.