본문 바로가기
카테고리 없음

looping array in go programming language

by Warehaus 2023. 5. 7.



Go is a powerful and efficient programming language that has gained popularity in recent years. 

 

One of the key features of Go is its support for loops, 

which allow you to execute a block of code repeatedly until a certain condition is met. 

 

In this article, we will explore the two types of for loops in Go and how to use them effectively.

 

Traditional for loop


The traditional for loop in Go is similar to other programming languages, with its syntax structured as follows:

for initialization; condition; increment/decrement {
    // code block to execute repeatedly
}



The `initialization` part of the for loop is optional, and it is used to initialize a variable before the loop starts. 

 

The `condition` part is evaluated before each iteration of the loop, and if it is true, the code block is executed. 

The `increment/decrement` part is executed after each iteration of the loop. 

 

 

Let's look at an example:

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



In this example, the for loop starts with `i` initialized to 0. 

 

The loop continues to execute as long as `i` is less than 5, and after each iteration, `i` is incremented by 1. 

The code block inside the for loop simply prints out the value of `i` on each iteration.

 


Range-based for loop


The range-based for loop in Go is used to iterate over arrays, slices, maps, strings, and channels. 

The syntax for the range-based for loop is as follows:

for index, value := range collection {
    // code block to execute repeatedly
}



The `index` variable represents the index of the current item in the collection, 

and the `value` variable represents the value of the current item. 

 

The `collection` can be an array, slice, map, string, or channel. 

 

Let's look at an example:


fruits := []string{"apple", "banana", "cherry"}
for index, value := range fruits {
    fmt.Println(index, value)
}



In this example, the range-based for loop iterates over an array of strings called `fruits`. 

 

On each iteration, the loop prints out the `index` and `value` of the current item. 

 

The output of this code would be:


0 apple
1 banana
2 cherry

 


Conclusion

 


In conclusion, for loops are a crucial part of any programming language, and Go is no exception. 

 

In this article, we explored the two types of for loops in Go - the traditional for loop and the range-based for loop. We also demonstrated how to use them effectively in your code. 

 

Whether you are a beginner or an experienced developer, mastering for loops is essential to becoming proficient in 

Go programming language.