The if-else expression in Golang

The if-statement is present in almost every programming language out there. It is one of the most important control-flow statements in programming. In this post, we will explore the different ways we can use the if statement to make our programs robust and concise.

1. The syntax of if-expression in GoLand

The syntax of the if-statement is pretty simple. The if statement evaluates an expression to a boolean value. If it is true then the code block afterward it executes else it doesn’t.

if cond {
        // do something...
}

Here is an example of a simple if expression.

package main

import (
	"fmt"
)

func main() {
	var v int = 42

	if v == 42 {
		fmt.Println("OK!")        // OK!
	}
}

Observe that in the program above, if the condition doesn’t match then nothing happens. No error is thrown.

2. The else clause

The else clause is used to redirect the control flow when the condition doesn’t match in the if expression. Here is an example of an if-else block.

package main

import (
	"fmt"
)

func main() {
	if 5 % 2 == 0 {
		fmt.Println("5 is divisible by 2")
	} else {      // else must be kept in the same line as the if block's end
		fmt.Println("5 is not divisible by 2")
	}
	
	// output: 5 is not divisible by 2
}

3. The else-if construct in Golang

Else-if is almost the same as if except the flow comes to it when the main if statement doesn’t match and it propagates downwards like a chain. Below is an example of an if-else-if-else chain.

package main

import (
	"fmt"
)

func main() {
	var v int = 12
	if v > 0 && v < 10 {
		fmt.Println("0-10")
	} else if v > 10 && v < 20 {
		fmt.Println("10-20")
	} else if  v > 20 && v < 30 {
		fmt.Println("20-30")
	} else {
		fmt.Println("30+")
	}    
	
	// output: 10-20
}

4. If statement with initialization

The if statement in Go can have an initialization at the very beginning. Here is the way to do it.

package main

import (
	"fmt"
)

func v() int {
	return 42
}

func main() {
	if a := v(); a == 42 {
		fmt.Println("It's 42")        // It's 42
	} else {
		fmt.Println("It's not")
	}
}

5. Nested if statements in Golang

If statements can be nested arbitrarily to any depth. Although too deeply nested if construct can lead to bad software design. Here we will explore an example of a nested if statement.

package main

import (
	"fmt"
)

func main() {
	var name string = "Rob"
	var age int     = 63
	
	if name == "Rob" {
		if age == 64 {
			fmt.Println("He is Rob.")
		} else {
			fmt.Println("Wrong person")
		}
	} else {
		fmt.Println("Who are you?")
	}
	
	// Wrong person
}

As you can see nesting can be of any depth. The if expression also replaces the needs for the ternary operator.

The if-else is an important control flow statement in the Go programming language.