Go For It

For

Similar to if, parentheses are not needed for conditions. Let’s built a factorial function using for

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
func factorial(n int) int {
if n == 0 {
return 1
}
res := 1
for i := 1; i <= n; i++ {
res *= i
}
return res
}

func main() {
fmt.Println(factorial(10))
}

The result outputs

1
3628800

Initial Value

Init value can be omitted. Let’s use for loop for a more complex application, convert decimal to binary:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package main

import (
"fmt"
"strconv"
)

func convertToBinary(n int) string {
res := ""
if n == 0 {
return "0"
}
for ; n > 0; n /= 2 {
lsb := n % 2
res = strconv.Itoa(lsb) + res
}
return res
}

func main() {
fmt.Println(
convertToBinary(8),
convertToBinary(13),
convertToBinary(0),
)
}

The results output

1
1000 1101 0

Incremental/Decremental

Incremental/Decremental steps can be omitted too. Let’s read a text file line by line

1
2
3
4
5
6
7
8
9
10
11
12
13
14
func printFile(filename string) {
file, err := os.Open(filename)
if err != nil {
panic(err)
}
scanner := bufio.NewScanner(file)
for scanner.Scan() {
fmt.Println(scanner.Text())
}
}

func main() {
printFile("abc.txt")
}

The result outputs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

Ending Condition

The ending condition can be omitted in Go as well. This will create an infinite loop, which can be really useful in some networking applications.
Also this will become really handy for Goroutines, which will be discussed later.

1
2
3
4
5
func forever() {
for {
fmt.Println("endless loop")
}
}

While

There’s no while loop in Go. while can be replaced by for completely.