Every programming language has some kind of loop for repeatedly executing a block of code. Programming languages like C/C++, C#, Python, Nodejs etc have their own way of writing loops. Among different types of loops the most common one is the for loop which almost all programming languages implement.
Example of a "for" loop
type Node struct {
Next *Node
Value interface{}
}
var first *Node
visited := make(map[*Node]bool)
for n := first; n != nil; n = n.Next {
if visited[n] {
fmt.Println("cycle detected")
break
}
visited[n] = true
fmt.Println(n.Value)
}
In the above example we traverse a linked list of Nodes and show it’s value, along the way we also detect if any cyclic relation present in the linked list.
As other programming languages implement different types of loops like while, for, foreach, do…while etc. On the other hand golang takes a different approach writing different types of loops using a single keyword for which we can say is a universal "for" loop.
Why universal, you may ask?
As other programming languages implement different types of loops, golang makes it’s "for" loop act as all(almost) types of loop.
Different types of loop in golang
1. Basic "for" loop or Three component loop
for init; condition; post_statement {
loop body
}
This is the basic way of writing a for loop in every programming language.
// Golang version
total := 0
for i := 1; i < 5; i++ {
total += i
}
fmt.Println(total) // (1+2+3+4) = 10
Summary of the above code:
we initialize the total variable to be 0. Then we initialize the for loop by saying – In the init statement we initialize the local variable i to 0 which scope is limited to the for loop.
- We put a condition statement.
i < 5
, which will be checked every time the loop starts again.- if true, the loops body code will be executed
- if false, the loops done with the execution.
- The post statement runs after the condition, and the loop body is executed. in the above code example it's incremented by 1.
- Back to step 2
2. "foreach" loop
for index, value := range array {
fmt.Println(`%v %v`, index, value)
}
Many languages give foreach to traverse or loop over elements of an array of items, maps etc. In Golang foreach loop can be easily achieved by using a for loop.
// Golang version
slice = []int{1,2,3} // array without a limit called slice
for i, v := range slice {
fmt.Println(i, v)
}
// Output
0 1
1 2
2 3
3. "While" loop
while condition {
fmt.Println(i)
i++ // i will be used to break from the loop
}
Generally, we use for loops when we know how many times the loop should run. On the other hand if we need to run a loop to fulfil a certain condition then we can use while loop. In golang we also use the "for" to write a while loop as golang doesn't provide a while keyword for writing it.we write it like the for loop but ignoring the init and post_statement part of a three component loop.
// Golang version
i := 1
for i < 5 {
i *= 2
}
fmt.Println(i) // (1*2*2*2) = 8
Summary of the above code:
we initialize the i variable to be 1. Then we initialize the "for" loop
- We check the condition statement. i < 5, which will be checked every time the loop starts again.
- if true, the loops body code will be executed
- if false, the loop is done with the execution.
- Back to step 1
4. "Infinite" loop
In the coding world we sometimes need to write an infinite loop. In other programming languages we use the while loop to write this.
n := 1
while true {
fmt.Println(n) // this will repeat forever
}
For golang we also achieve this by writing a for loop.
// Golang version
i := 1
for {
i++ // this will repeat forever
}
fmt.Println(i) // this line will never be executed.
we just ignore the condition part of a while loop to make the loop statement an infinite loop.Also note that if we want to break from an infinite loop we need to put a base condition inside the infinite loop.
// Golang version
i := 1
for {
i++
if i > 10 {
break // will break the infinite loop when i value reach 10
}
}
fmt.Println(i) // 11
5. "do…while" loop
The basic idea of a "do…while" loop is to run a block of code at least one time then check the condition
- if true, the loops body code will be executed.
- if false, the loops done with the execution.
do {
print(i)
i++ // i will be used to break from the loop
} while(i < 10)
So golang we can write the above scenario in two ways
// 1st way
for ok := true; ok; ok = condition {
work()
}
// 2nd way
for {
work()
if !condition {
break
}
}
In summary a "do…while" loop, the condition will be checked after the code block runs at least once.
This post also published as github gist.
Conclusion
As other programming language gives different keywords and syntax for writing loops, golang takes a slightly different approach and make it's for loop act as other loops. So now we can conclude our post by saying "Golangs for loop, can act as universal loop."