Hurry! Try our new Interactive Courses for FREE. 🥳   🚀

If-Else in Go

Until now, we have seen that a Go program starts executing in main() and sequentially executes the statements in that function. However, we often want to execute certain statements only if a condition is met, which means we want to make decisions in our code. For this purpose, Go provides conditional statements such as if, if-else, etc.

if Statement in Go

The first variant of the if statement looks something like this:

if condition {
    // do something
}

The if tests a conditional statement. That statement can be logical or boolean. If the statement evaluates to true, the body of statements between { } is executed, and if it is false, these statements are ignored and the statement following the if after } is executed.

if-else statement in Go

The second variant of the if statement looks something like this:

if condition {
   // do something
} else {
   // do something else
}

In a 2nd variant, an else, with a body of statements surrounded by { }, is appended, which is executed when the condition is false. It means we have two exclusive branches, and only one of them is executed.

In a 3rd variant, another if condition can be placed after the else, so we have 3 exclusive branches.

if-else if-else statement in Go

The third variant of the if statement looks something like this:

if condition1 {
   // do something
} else if condition2 {
   // do something else
} else {
   // default 
}

The number of else if branches are in principle, not limited, but for readability reasons, the use of else if should not be exaggerated. It is recommended that when you have multiple if-else branches then you should try to place the condition which is most likely to be true first, as it will improve the execution speed of your program.

It should also be noted that the { } braces are mandatory even when there is only one statement in the body. The opening brace must be on the same line as the if keyword and the else clause must be on the same line as the closing brace of the previous if or else if keyword.

Consider the below cases which will make it clear.

if x == 2 {
   // do something
} else {
   // do something else
}

The above code is perfectly valid as both the braces are on the same line as the if and the else keyword and also the else keyword is just after the closing brace of the if block.

Consider the code snippet shown below is not valid.

if x == 2 {
   // do something
} 
else {
   // do something else
}

It should also be noted that unlike other famous programming languages it is not required of you to put parentheses around the conditions of the if-else statements. Let's explore a simple example of the if-else statement where you will notice that we won't make use of any parentheses.

Example: if-else example in Go

Consider the example shown below:

package main

import (
	"fmt"
)

func main() {
	var n int = 11

	if n%2 == 0 {
		fmt.Println("The number is even")
	} else {
		fmt.Println("The number is odd")
	}
}


The number is odd

Example: if statement example in Go

The condition that we pass after the if keyword in an if/else construct is a bool condition, and instead of having an expression like in the example above we can also pass bool values.

Consider the example shown below:

package main

import (
	"fmt"
)

func main() {
	if true {
		fmt.Println("Will always print!")
	} 
}


Will always print!

Example: Nested If-Else in Go

In Go, it is very common to have if-else statements that are present inside another if-else statement.

Consider the example shown below that depicts a case where we have an if statement inside another if statement.

package main

import (
	"fmt"
)

func main() {
	var count int
	for count < 10 {
		count++
		if count > 5 || count < 10 {
			if count == 6 {
				fmt.Println("Count is 6")
				break
			} else if count == 8 {
				fmt.Println("Count is 8")
				continue
			}
		}
		fmt.Println("The count is:", count)
	}
	fmt.Println("Loop ended")
}

In the above example, we are having an if-else construct inside an if statement, which depicts the case of nested if-else.


The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
Count is 6
Loop ended

If-else ladder in Go

If-else ladder is a programming construct that is entirely based on the nested ifs. It looks something like this.

if condition 1 {
   statement 1
} else if condition 2 {
   statement 2
} else if condition 3 {
   statement 3
}
.
.
.

The conditional expression shown in the above examples are evaluated from the top to the bottom and as soon as we find any condition which evaluates to true, the statement that is associated with it will be executed, and the rest of the ladder will be bypassed. If we don't encounter a single statement that evaluates to true, then the final else statement will be executed. In this if-else ladder, the final else statement often acts as a default statement.

Example: If-else ladder in Go

package main

import (
	"fmt"
)
func main() {
	   
   var v1 int = 200
   if(v1 == 100) {
      fmt.Printf("Value of v1 is 100\n")
   } else if(v1 == 200) {
      fmt.Printf("Value of a is 20\n")
   } else if(v1 == 300) {
      fmt.Printf("Value of a is 300\n")
   } else {
      fmt.Printf("None of the values is matching\n")
   }
}


Value of a is 20

Conclusion

In this tutorial, we learned what if/else statements are, how to write them in Go, and we also learned about the cases that we don't have to include any parentheses in the conditions and finally, we saw different examples of if/else statements in Go.