ZetCode

Go if & else statements

last modified July 9, 2020

Go if & else statements tutorial shows how to create conditions and branches in Golang.

Go if & else

The if statement specifies the conditional execution of a block. If the expression evaluates to true, the block is executed. If the else statement is present and the if statement evaluates to false, the block following else is executed.

There can be multiple if/else statements.

Go if/else examples

The following examples demonstrate conditional execution of blocks with if/else.

if_stm.go
package main

import "fmt"

func main() {
    
    num := 4
    
    if num > 0 {

        fmt.Println("The number is positive")
    }
}

In the example we have a simple condition; if the num variable is positive, the message "The number is positive" is printed to the console. Otherwise; nothing is printed.

$ go run if_stm.go 
The number is positive

The message is printed since value 4 is positive.

if_else.go
package main

import "fmt"

func main() {
    
    num := -4
    
    if num > 0 {

        fmt.Println("The number is positive")
    } else {

        fmt.Println("The number is negative")
    }
}

Now we have added the second branch. The else statement specifies the block that is executed if the if condition fails.

$ go run if_else.go 
The number is negative

For the -4 value, the "The number is negative" is printed.

if_else2.go
package main

import (
    "fmt"
    "math/rand"
    "time"
)

func main() {
    
    rand.Seed(time.Now().UnixNano())

    num := -5 + rand.Intn(10)

    if num > 0 {

        fmt.Println("The number is positive")
    } else if num == 0 {

        fmt.Println("The number is zero")
    } else {

        fmt.Println("The number is negative")
    }
}

In this example, we add additional branch with if else. We generate random values between -5 and 4. With the help of the if & else statement we print a message for all three options.

$ go run if_else2.go 
4
The number is positive
$ go run if_else.go 
0
The number is zero
$ go run if_else.go 
-5
The number is negative

We run the example a few times.

In this tutorial, we have covered conditions in Golang.

List all Go tutorials.