Don't miss this free $200 USD credit (Valid for 60 days) on DO, launch your idea now

You have no excuses now, use this free credit to launch your projects now on Digital Ocean, you're free to spend it whenever you want within the following 60 days.

Table of contents

Go: loops for, break, continue, defer, if and else

Go: loops for, break, continue, defer, if and else

This entry will deal with loops in the go programming language.

Hey! did you know that I wrote a completely Free Go programming language tutorial?, you can find it directly in the top menu bar or clicking this box.

Go handles loops a little differently than what you are used to. If you’re already fluent in any other programming language, you probably remember while, do while and for loops. And if you come from Python or Javascript, you’ll remember how useful for x in or for x of loops are.

Well, as there are more than enough loops for. Yes, there is no while or do while. But then how do I use the rest of the loops? Read on and I’ll explain.

If you don’t know anything about Go and want to start with the basics visit my entry Golang: introduction, variables and data types .

If you currently use Python and want to see how it is different from Go, visit my python vs go post.

If and else

If_ and else allow you to execute blocks of code conditionally and keep the same syntax as in almost all languages.

if true {
    fmt.Println("True")
} else {
    fmt.Println("False")
}

else if

And of course go also has an else if.

edad := 18
if edad < 18 {
    fmt.Println("Underage")
} else if edad > 18 {
    fmt.Println("Adult")
} else {
    fmt.Println("Exactly 18 years old")
}

Loops for in go

In go there are several types of for loops: counter, conditional, range and infinite.

Loops with counter

This is the classic loop that you already know from Javascript, C++, etc. In which you declare a variable, specify a condition, and make changes to the variable.

We declare “i” equal to 0, as long as “i” is less than 10, it executes the next block and subsequently increments “i” by one, each instruction separated by a semicolon.

for i:= 0; i < 10; i++ {
    // ...
}

Loop with conditional

In this type of loop a condition is evaluated, if the result is true, the block is executed, if not, that block of code is skipped. This type of for loop would be the equivalent of the while loop.

counter := 0
for counter < 10 {
    counter ++
}

Loop with range

Range allows us to traverse an iterable structure from beginning to end and allows us to access the respective index and element. It is ideal for traversing arrays, strings, slices, maps, channels and any structure that can be traversed.

HelloWorld := "Hello world"
    for index, letra := range HelloWorld {
    	fmt.Printf("%d %c \n", index, letra)
    }
/*
0  H 
1  e 
2  l 
3  l 
4  o  
5   
6  w 
7  o 
8  r 
9  l
10 d*/

Infinite loop

A for loop without condition will run forever.

The only way to get out of an infinite for loop is with a break.

counterForever := 0
for {
    counterForever++
}

break

As I just mentioned, break breaks a loop and continues code execution.

counterForever := 0
for {
    counterForever++
    fmt.Println(counterForever)
    if counterForever > 5 {
        fmt.Println("The loop breaks here")
        break
}
}
// 1
// 2
// 3
// 4
// 5
// 6
// The loop breaks here

Break in loops with name in go

In other programming languages, such as Python, break would break the immediate loop, i.e. the immediate loop it is in. Wouldn’t it be great to be able to stop the outer loop from the inner loop? In go it is possible in a simple way

while True:
    while True:
        break
    println("main loop is executing")
# main loop is executing
# main loop is executing
# main loop is executing

Go allows us to assign names to the loops, what for? To reference specific loops and be able to break them using break. Take a look at this example:

loop:
    for {
    	for {
    		fmt.Println("Breaking external loop")
    		break loop
    	}
    	fmt.Println("This will never get printed")
    }

We name our loop as loop and now we execute an infinite loop that will have an infinite loop inside it. This last loop will break the outer loop, named loop, so the second statement will never be printed on the screen.

continue

Continue stops the current iteration of the loop and continues its execution in the next iteration.

counter := 0
for counter < 10 {
    counter ++
    if counter == 3 {
        fmt.Println("We skip number 3")
        continue
    }
    fmt.Println(counter)
}
//1
//2
//We skip number 3
//4

defer

Defer delays the execution of a line of code until the end of the code. It is quite similar to what the defer attribute with HTML script tag does.

defer fmt.Println("This will be executed at the end")
    fmt.Println("This will be executed firstly")
    fmt.Println("This will be executed secondly")
// This will be executed firstly
// This will be executed secondly
// his will be executed at the end

What’s the point? Well, it is ideal to close connections to databases, files or to make some type of cleaning to the objects of our code.

const dbConnection := openDb()
defer closeDb()
queryDb()
anoterQuery()

For the next Go entry I’m going to talk about the basics of slices, arrays and maps.

Remember that you can visit the official go documentation if there is anything you want to learn more about.

Eduardo Zepeda
Web developer and GNU/Linux enthusiast. I believe in choosing the right tool for the job and that simplicity is the ultimate sophistication. Better done than perfect. I also believe in the goodness of cryptocurrencies outside of monetary speculation.
Read more