Flow control
Flow control is referred as the ability to decide which portion of code or how many times you execute some code on a condition. In Go, it is implemented using familiar imperative clauses like if, else, switch and for. The syntax is easy to grasp. Let´s review major flow control statements in Go.
The if... else statement
Go language, like most programming languages, has if…else
conditional statement for flow control. The Syntax is similar to other languages but you don't need to encapsulate the condition between parenthesis:
ten := 10 if ten == 20 { println("This shouldn't be printed as 10 isn't equal to 20") } else { println("Ten is not equals to 20"); }
The else...if
condition works in a similar fashion, you don't need parentheses either and they are declared as programmer would expect:
if "a" == "b" || 10 == 10 || true == false { println("10 is equal to 10") } else if 11 == 11 &&"go" == "go" { println("This isn't print because previous condition was satisfied"); } else { println("In case no condition is satisfied, print this") } }
Note
Go does not have ternary conditions like condition ? true : false
.
The switch statement
The switch
statement is also similar to most imperative languages. You take a variable and check possible values for it:
number := 3 switch(number){ case 1: println("Number is 1") case 2: println("Number is 2") case 3: println("Number is 3") }
The for…range statement
The _for_
loop is also similar than in common programming languages but you don't use parentheses either
for i := 0; i<=10; i++ { println(i) }
As you have probably imagined if you have computer science background, we infer an int
variable defined as 0
and execute the code between the brackets while the condition (i<=10
) is satisfied. Finally, for each execution, we added 1
to the value of i
. This code will print the numbers from 0 to 10. You also have a special syntax to iterate over arrays or slices which is range
:
for index, value := range my_array { fmt.Printf("Index is %d and value is %d", index, value) }
First, the fmt
(format) is a very common Go package that we will use extensively to give shape to the message that we will print in the console.
Regarding for, you can use the range
keyword to retrieve every item in a collection like my_array
and assign them to the value temporal variable. It will also give you an index
variable to know the position of the value you're retrieving. It's equivalent to write the following:
for index := 0, index < len(my_array); index++ { value := my_array[index] fmt.Printf("Index is %d and value is %d", index, value) }
Tip
The len
method is used to know the length of a collection.
If you execute this code, you'll see that the result is the same.