If else statement

Welcome to tutorial number 8 of our Golang tutorial series.

if statement has a condition and it executes a block of code if that condition evaluates to true. It executes an alternate else block if the condition evaluates to false. In this tutorial we will look at the various syntaxes for using a if statement.

If statement syntax

The syntax of the if statement is provided below

if condition {
}

If the condition evaluates to true, the block of code between the braces { and } is executed.

Unlike in other languages like C, the braces { } are not optional and they are mandatory even if there is only one line of code between the braces{ }.

Example

Let’s write a simple program to find out whether a number is even or odd.

 1package main
 2
 3import (
 4	"fmt"
 5)
 6
 7func main() {
 8	num := 10
 9	if num%2 == 0 { //checks if number is even
10		fmt.Println("The number", num, "is even")
11		return
12	}
13	fmt.Println("The number", num, "is odd")
14}

Run in Playground

In the above program, the condition num%2 in line no. 9 finds whether the remainder of dividing num by 2 is zero or not. Since it is 0 in this case, the text The number 10 is even is printed and the program exits.

If else statement

The if statement has an optional else construct which will be executed if the condition in the if statement evaluates to false.

if condition {
} else {
}

In the above snippet, if condition evaluates to false, then the block of code between else { and } will be executed.

Let’s rewrite the program to find whether the number is odd or even using if else statement.

 1package main
 2
 3import (
 4	"fmt"
 5)
 6
 7func main() {
 8	num := 11
 9	if num%2 == 0 { //checks if number is even
10		fmt.Println("The number", num, "is even")
11	} else {
12		fmt.Println("The number", num, "is odd")
13	}
14}

Run in playground

In the above code, instead of returning if the condition is true as we did in the previous section, we create an else statement that will be executed if the condition is false. In this case, since 11 is odd, the if condition is false and the lines of code within the else statement is executed. The above program will print.

The number 11 is odd

If … else if … else statement

The if statement also has optional else if and else components. The syntax for the same is provided below

if condition1 {
...
} else if condition2 {
...
} else {
...
}

The condition is evaluated for the truth from the top to bottom.

In the above statement, if condition1 is true, then the block of code within if condition1 { and the closing brace } is executed.

If condition1 is false and condition2 is true, then the block of code within else if condition2 { and the next closing brace } is executed.

If both condition1 and condition2 are false, then the block of code in the else statement between else { and } is executed.

There can be any number of else if statements.

In general, whichever if or else if’s condition evaluates to true, it’s corresponding code block is executed. If none of the conditions are true then else block is executed.

Let’s write a bus ticket pricing program using else if. The program must satisfy the following requirements.

  • If the age of the passenger is less than 5 years, the ticket is free.
  • If the age of the passenger is between 5 and 22 years, then the ticket is $10.
  • If the age of the passenger is above 22 years, then the ticket price is $15.
 1package main
 2
 3import (
 4	"fmt"
 5)
 6
 7func main() {
 8	age := 10
 9	ticketPrice := 0
10	if age < 5 {
11		ticketPrice = 0
12	} else if age >= 5 && age <= 22 {
13		ticketPrice = 10
14	} else {
15		ticketPrice = 15
16	}
17	fmt.Printf("Ticket price is $%d", ticketPrice)
18}

Run in playground

In the above program, the age of the passenger is set to 10. The condition in line no. 12 is true and hence the program will print

Ticket price is $10

Please try changing the age to test whether the different blocks of the if else statement are executed as expected.

If with assignment

There is one more variant of if which includes an optional shorthand assignment statement that is executed before the condition is evaluated. Its syntax is

if assignment-statement; condition {
}

In the above snippet, assignment-statement is first executed before the condition is evaluated.

Let’s rewrite the program which calculates the bus ticket price using the shorthand syntax.

 1package main
 2
 3import (
 4	"fmt"
 5)
 6
 7func main() {
 8	ticketPrice := 0
 9	if age := 10; age < 5 {
10		ticketPrice = 0
11	} else if age >= 5 && age <= 22 {
12		ticketPrice = 10
13	} else {
14		ticketPrice = 15
15	}
16	fmt.Printf("Ticket price is $%d", ticketPrice)
17}

Run in playground

In the above program age is initialized in the if statement in line no. 9. age can be accessed from only within the if construct. i.e. the scope of age is limited to the if, else if and else blocks. If we try to access age outside the if, else if or else blocks, the compiler will complain.
This syntax often comes in handy when we declare a variable just for the purpose of if else construct. Using this syntax in such cases ensures that the scope of the variable is only within the if statement.

Gotcha

The else statement should start in the same line after the closing curly brace } of the if statement. If not the compiler will complain.

Let’s understand this by means of a program.

 1package main
 2
 3import (
 4	"fmt"
 5)
 6
 7func main() {
 8	num := 10
 9	if num % 2 == 0 { //checks if number is even
10		fmt.Println("the number is even") 
11	}  
12    else {
13		fmt.Println("the number is odd")
14	}
15}

Run in playground

In the program above, the else statement does not start in the same line after the closing } of the if statement in line no. 11. Instead, it starts in the next line. This is not allowed in Go. If you run this program, the compiler will print the error,

./prog.go:12:5: syntax error: unexpected else, expected }

The reason is because of the way Go inserts semicolons automatically. You can read about the semicolon insertion rule here https://go.dev/ref/spec#Semicolons.

In the rules, it’s specified that a semicolon will be inserted after closing brace }, if that is the final token of the line. So a semicolon is automatically inserted after the if statement’s closing braces } in line no. 11 by the Go compiler.

So our program actually becomes

1...
2if num%2 == 0 { 
3      fmt.Println("the number is even") 
4};  //semicolon inserted by Go Compiler
5else {
6      fmt.Println("the number is odd")
7}

after semicolon insertion. The compiler would have inserted a semicolon in line no. 4 of the above snippet.

Since if{...} else {...} is one single statement, a semicolon should not be present in the middle of it. Hence this program fails to compile. Therefore it is a syntactical requirement to place the else in the same line after the if statement’s closing brace }.

I have rewritten the program by moving the else after the closing } of the if statement to prevent the automatic semicolon insertion.

 1package main
 2
 3import (
 4	"fmt"
 5)
 6
 7func main() {
 8	num := 10
 9	if num%2 == 0 { //checks if number is even
10		fmt.Println("the number is even") 
11	} else {
12		fmt.Println("the number is odd")
13	}
14}

Run in playground

Now the compiler will be happy and so are we ๐Ÿ˜ƒ.

Idiomatic Go

We have seen various if-else constructs and we have in fact seen multiple ways to write the same program. For example, we have seen multiple ways to write a program that checks whether the number is even or odd using different if else constructs. Which one is the idiomatic way of coding in Go? In Go’s philosophy, it is better to avoid unnecessary branches and indentation of code. It is also considered better to return as early as possible. I have provided the program from the previous section below,

 1package main
 2
 3import (
 4	"fmt"
 5)
 6
 7func main() {
 8	if num := 10; num % 2 == 0 { //checks if number is even
 9		fmt.Println(num,"is even") 
10	}  else {
11		fmt.Println(num,"is odd")
12	}
13}

Run in playground

The idiomatic way of writing the above program in Go’s philosophy is to avoid the else and return from the if if the condition is true.

 1package main
 2
 3import (
 4	"fmt"
 5)
 6
 7func main() {
 8	num := 10;
 9	if num%2 == 0 { //checks if number is even
10		fmt.Println(num, "is even")
11		return
12	}
13	fmt.Println(num, "is odd")
14
15}

Run in playground

In the above program, as soon as we find out the number is even, we return immediately. This avoids the unnecessary else code branch. This is the way things are done in Go ๐Ÿ˜ƒ. Please keep this in mind whenever writing Go programs.

I hope you liked this tutorial. Please leave your feedback and comments. Please consider sharing this tutorial on twitter or LinkedIn. Have a good day.

Next tutorial - Loops