Go If Statement Example

Go If Statement, Introduction to Flow Control

 

So, now that we have an understanding of variables in Go let’s do something more interesting with them than just printing them out to the screen. So far all of the programs that we’ve written have been completely linear. They start at the top and line by line execute every statement in order unconditionally. This execution flow is pretty limiting in what it allows us to do. It’s time to introduce what in programming is referred to as flow control. This is simply the concept of introducing conditions into our program that can affect what code we execute when or if we execute it at all. The first flow control statement we’ll talk about is the Go if statement.

To get started with our new project create a new folder inside your GOPATH/src folder. I’ve named this folder “ifstatement” on my computer. Just like in the Variables in Go project create a folder named “main” inside the project directory and create a main.go file inside of it. Put the following template code in the main.go file, hopefully, this is starting to become familiar to you.

1
2
3
4
5
6
7
8
9
package main

import (

)

func main () {

}

The Go If Statement

The Go If Statement evaluates whether or not a specified condition is true. If the statement is true then it will execute the code in the block that follows. A block is all of the code between an opening brace { and a closing brace }. For the simplest version of the Go if statement it’s worth introducing booleans. A boolean is a data type with two possible values, it’s either true or it’s false. In Go, the type for representing booleans is “bool”.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package main

import (
    "fmt"
)

func main () {
    var myBool bool
    myBool = true

    if myBool == true {
        fmt.Println("myBool is true!")
    }
}

Now, this is a pretty explicit example to make sure it’s as clear as possible what the code is doing as we’re introducing a few new concepts at once. The first thing we’re doing is declaring (creating) a new variable with the type bool. Then we’re setting our variable “myBool” to have a value of true. Finally, we have an if statement that checks if the value of myBool is true. If it is true then we’ll execute the code in the block, which prints out “myBool is true!”. The double equals sign (==) means that we want to compare the value on the left to the value on the right to see if they’re equal, as opposed to the single equals sign (=) which is used to assign a value to a variable.

Like I mentioned, we’re being overly verbose here. The Go if statement evaluates if a statement is true. A comparison operation like we’re doing returns true or false which the if statement then evaluates. However our myBool variable is a boolean, so it’s value is already true or false. This means that we could just directly check if our myBool is true without using the comparison at all. Let’s update our code to make the comparison of myBool implicit. While we’re at it let’s set myBool to false and add a Go if statement that checks if myBool is false and print “myBool is false!” if that’s the case.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package main

import (
    "fmt"
)

func main () {
    var myBool bool
    myBool = true

    if myBool {
        fmt.Println("myBool is true!")
    }

    myBool = false

    if ! myBool {
        fmt.Println("myBool is false!")
    }
}

In addition to just having the Go if statement check whether or not myBool is true implicitly, we’ve also introduced negation. The negation operator (!) inverts whatever statement follows it. So our second if statement checks if myBool is NOT true.

If Else

While having two separate if statements in our code accomplishes what we want, it’s not a very concise way of writing our program. Having two if statements implies that they are two unrelated and independent actions. Really what we are trying to do though is say that if one condition is true then do something otherwise we want to do something else.

Thankfully we have a method for doing that. The Go if statement has an optional else component. Else does exactly what it sounds like, we have our Go if statement and when the condition evaluates as true we’ll execute the code in the following block we then can have an else statement and a second code block. When the condition of the if statement is not true we’ll execute the code in the block that follows the else statement instead. The else statement must always be on the same line as the closing brace } of the if statement block as shown below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package main

import (
    "fmt"
)

func main () {
    var myBool bool
    myBool = false

    if myBool {
        fmt.Println("myBool is true!")
    } else {
        fmt.Println("myBool is false!")
    }
}

In this example because myBool is set to false the conditional expression of the Go if statement was false and it’s associated block was not executed. Instead, because the condition was not met we executed the block associated with the else statement. When written as just “else” the block that follows the else will always execute when a previous if condition was not true.

Else If

Alternatively, we can also associate a condition with the else by using another Go if statement with the else. In this case, we will only execute the block when the previous if condition was not met AND the condition associated with the else is met.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package main

import (
    "fmt"
)

func main () {
    myNumber := 4

    if myNumber % 2 == 1 {
        fmt.Println("myNumber is odd!")
    } else if myNumber % 2 == 0{
        fmt.Println("myNumber is even!")
    }
}

The modulo (%) operator divides the number on the left by the number on the right and returns the remainder. So 4 % 2 returns 0, whereas 5 % 2 would return 1. In this example, we check if the remainder of myNumber (which is 4) divided by 2 equals (==) 1. If that’s true then myNumber (which is 4) would be odd. If the first Go if statement is not true (which is the case) then we’ll move on to the else if statement. This statement checks if the remainder of myNumber divided by 2 equals 0. This time our statement is true, so we execute the next block, which is to print “myNumber is even!”.

Putting it All Together

You can have as many else if statements with your Go if statement as you would like, but you can only have one plain else statement and it must be last.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package main

import (
    "fmt"
)

func main () {
    myNumber := 9

    if myNumber % 2 == 0 {
        fmt.Println("myNumber is devisible by two!")
    } else if myNumber % 5 == 0 {
        fmt.Println("myNumber is devisible by five!")
    } else {
        fmt.Println("myNumber isn't divisible by two or five!")
    }
}
Chris Sotherden

Originally a native of upstate NY, I relocated to North Carolina in 2013 where I've since helped open the new R&D headquarters for Optanix. I've been with Optanix (formerly ShoreGroup) for over ten years, where I've worked my way up from entry-level to Lead Architect. I taught myself programming in high school and am an all around technology nerd from the design of programming languages and compilers, to quantum computing, and rockets. Outside of technology I've competed in powerlifting and medium distance running, as well as smoking some mean BBQ. Oh, my partner and I also breed, show, and sell fancy goldfish!

>