Go: Looping (Part 5)

This is a fifth post on Go programming language. You can read first, second, third and forth post if you are reading this post for the first time. These posts will give you necessary background.

Go supports the iteration statement via for language construct. Using for keyword, you can write for loop and a while loop. Go does not have support for do...while loop construct. The basic component of for loop is - initializer, condition and post statement. Like if statement, you don't have to wrap these components in parenthesis. For example, here is the loop.go program that print numbers from 0 to 4.

package main

import "fmt"

func main() {
    var i int

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

Running this program will produce following output.

$ go run loop.go
0
1
2
3
4

A while loop can be written using for keyword because initializer and the post statement are optional in above for syntax. Here is the same program while.go that print 0 to 4 but in while format.

package main

import "fmt"

func main() {
    var i int = 0

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

Running this program produce the same identical output.

$ go run while.go
0
1
2
3
4

In the above program, I wrapped the condition using semicolons. But, these semicolons are actually optional if you want to feel it like while loop. So, dropping these semicolons do not effect the output and it will remain same identical.

package main

import "fmt"

func main() {
    var i int = 0

    for i < 5 {
        fmt.Println(i)
        i++
    }
}

Not just initializer and post statement, but a conditional statement is also optional. You can remove it from the for loop. But, be careful! It will create an infinite loop because nothing there in for syntax to stop it!

package main

import "fmt"

func main() {
    var i int = 0

    for {
        fmt.Println(i)
        i++
    }
}

With the knowledge of condition and looping, we can print the odd numbers between 0 to 10. Let's create the program with name odd.go and write the basic skeleton program inside of it.

package main

import "fmt"

func main() {
    var i int

}

Here, I defined one variable with name i for looping. We know how to print numbers from 0 to 10, right?

package main

import "fmt"

func main() {
    var i int

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

You can write i <= 10. I do not have problem with that condition statement. From the previous post, you know how to find the given number is odd or even right? If i % 2 == 0 then given number is even. But, hey we are not interested in finding even numbers. We are actually interested in finding odd numbers. So, our condition will be tweak a little bit like i % 2 != 0 then given number is odd. Also, where should I put? Inside loop because at that place I will get the value of i.

Let's update our program with the above discussion.

package main

import "fmt"

func main() {
    var i int

    for i = 0; i < 11; i++ {
        if i % 2 != 0 {
            fmt.Println(i)
        }
    }
}

Running this program will produce following output.

go run odd.go
1
3
5
7
9

That's what we want!

Before we go further and solve some other problems, let me give a little tip on declaration of variables. You know how to define a variable with its initial value, right?

var i int = 0

If you know the initial value of given variable, you can remove the type from its declaration. Because, based on initial value Go compiler will automatically assign the proper type. So, the following code is also valid in Go.

var i = 0

Go will auto define i as int type for you based on initial value. If you define variable like this,

var pi = 3.14

Go will auto define pi as float64 type. If you define variable like this,

var name = "Bruce"

Go will auto define name as string type. Auto assigning the type to the variable based on its initial value is known as type inference.

Let me go further and tell you that, if you know the initial value of variable then you even don't have to write var keyword. You can directly define the variable. But, in this case, you need to use := operator instead of = operator. So, following all three declaration are valid and equivalent.

var i int = 23
var i = 23
i := 23

With the help of this short-hand notation, I can reduce one line from odd.go program as below.

package main

import "fmt"

func main() {
    for i := 0; i < 11; i++ {
        if i % 2 != 0 {
            fmt.Println(i)
        }
    }
}

That's it for looping. Floor is open for questions.

I know other programming language that supports break statement. Does go support?: Of course! Go supports both break and continue statements. For example the above program can be written as follow in continue.go program.

package main

import "fmt"

func main() {
    for i := 0; i < 11; i++ {
        if i % 2 == 0 {
            continue
        }
        fmt.Println(i)
    }
}

Why they do not provide while loop?: I showed you an example of while loop. But, if you are speaking about while keyword. The I don't know. Personally speaking, I'm quite happy with the direction they take - just a simple for loop for iteration - less to remember. On the other hand languages like JavaScript has for, while, do...while, for...in, for...of, and .forEach(). I mean six constructs just for looping!

You pointed out that if I define a variable like pi := 3.14 then it become float64. I want to make it float32, how can I do this?: No you can't. If you are using type inference, Go compiler will do it for you. You can define it as float32 except var pi float32 = 3.14.

Why you don't first tell me out this :=?: Just to make yourself little comfortable with type system. Also, in future when you involve in real world project, you don't just expect them to use only one type of declaration. They used anyone they like!


chabad360 picture

Is there a way to do for each ... in in Go?

chabad360 picture

Would you be able to include that in this, or a future part?

Minenash picture

I'm not the author :P