In Go, you can use both for
and while
loops for iterative tasks. Here's how you can create and use these loops:
for
loop in Go has a variety of formats to suit different use cases. Here are two common ways to use it:for i := 0; i < 5; i++ {
// Code to be executed repeatedly
fmt.Println(i)
}
This loop starts with initializing a counter variable (i
in this case), specifies the condition under which the loop will run (i < 5
), and defines how the counter should be incremented after each iteration (i++
).
arr := [3]string{"Apple", "Banana", "Cherry"}
for index, value := range arr {
// Code to be executed repeatedly
fmt.Printf("Index: %d, Value: %s\n", index, value)
}
Here, the loop iterates over the elements of the arr
array using the range
keyword. On each iteration, it assigns the index and the value of the current element to the respective variables (index
and value
in this example).
while
loop construct. However, you can achieve the same functionality using a for
loop with a single condition:i := 0
for i < 5 {
// Code to be executed repeatedly
fmt.Println(i)
// Increment the counter
i++
}
This loop runs until the condition (i < 5
) is false. You can place any conditional statement that evaluates to a boolean value inside the loop condition.
These are the basic ways to create and use loops in Go using for
and while
concepts. Feel free to adapt them as per your specific requirements.