Conditionals and Loops

Chapter 6

If Statements#

If statements in Go do not require any parentheses.

if x > 10 {
fmt.Println("I'm more than 10!")

If can have a short statement before the condition:

if x := 10 * 2; x < 50 {
return x
} else {
return 10

Note that, in the above example, x is only available for use in the lexical scope of the if and else statements. Hence, it cannot be referenced anywhere outside this scope.

Switch Statements#

When we have a sequence of conditions to check, it will be easier to use the switch statement.

func main() {
color := "blue"
switch color {
case "blue":
fmt.Println("The color is blue!");
case "red":
fmt.Println("The color is red!")
fmt.Println("No valid colour set.")

We can also construct a switch statement without a condition. This is the same as saying `switch true.

Switch statements by default have an implicit break without them being explicitly included. This means that once a case matches the condition, it evaluates it and stops there.

Flow Control#

Go only has one looping construct - the forloop.

func main() {
// method 1: similar to a while loop in other languages
i := 5
for i > 0 {
// method 2: the well-known for loop construct
for j := 5; j > 0; j-- {
// method 3: without any conditions - similar to a while(true) loop in other languages
for {
fmt.Println("I will only print once!")

There are three ways to use the for loop in Go. You can make out similarities to while loops as in other languages if you are used to them.

Most importantly, the loops are pretty logical and its very "readable".

Notes: {} are always required. No parentheses, (), needed for the three components in the for loop declaration.