Working with If Else in Go

11.16.2021

Intro

Go provides us with the common if, else if, and else control statements that you would expect from programming languages. These statements allow you to branch and run code based on conditions. In this article we will learn if else in Go.

If Statements

We can start of with the basic if statement. We use {} to create blocks and the code inside the block will be executed if the condition is met.

age := 18

if age < 21 {
	fmt.Println("You are two young")
}

Else If Statements

We can connect multiple if statements together using the else if. This allows us to check a second condition if the first condition fails.

age := 64

if age < 21 {
	fmt.Println("You are two young")
} else if age > 60 {
	fmt.Println("You can have the senior discount")
}

Else Statement

Our final example uses the else statement. This will run code if all other conditions fail.

age := 22

if age < 21 {
	fmt.Println("You are two young")
} else if age > 60 {
	fmt.Println("You can have the senior discount")
} else {
	fmt.Println("You will have to pay full price")
}

The Full Example

The full code is provided below. Simply copy this code to a file called main.go then run go run main.go.

package main

import "fmt"

func main() {
	age := 18

	if age < 21 {
		fmt.Println("You are two young")
	}

	age = 64

	if age < 21 {
		fmt.Println("You are two young")
	} else if age > 60 {
		fmt.Println("You can have the senior discount")
	}

	age = 22

	if age < 21 {
		fmt.Println("You are two young")
	} else if age > 60 {
		fmt.Println("You can have the senior discount")
	} else {
		fmt.Println("You will have to pay full price")
	}
}