Conditional Statements in Go

Conditional Statements in Go

In this tutorial, we are going to discuss about conditional statements in Go language. Conditional statements are part of every programming language.

With conditional statements, we can have code that sometimes runs and at other times does not run, depending on the conditions of the program at that time.

Conditional Statements in Go

Go language providesΒ if/elseΒ andΒ switchΒ conditional statements for code execution based on certain conditions.

if statement

We will start with the if statement, which will evaluate whether a statement is true or false, and run code only in the case that the statement is true.

The syntax of the if statement is provided below

if condition {   
}

If the condition is true, the lines of code between the braces { and } is executed.

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

E.g

package main

import "fmt"

func main() {
     marks := 85
     if marks >= 35 {     
        fmt.Println("Congratulations you have passed exam..!!)
     }
}

Output

Congratulations you have passed.!!

Run in playground

With this code, we have the variable marks and are giving it the integer value of 85. We are then using the if statement to evaluate whether or not the variable grade is greater than or equal ( >= ) to 65.

If it does meet this condition, we are telling the program to print out the string Congratulations you have passed.!!

Let’s now change the result of this program by changing the value of the marks variable to 30

E.g

package main

import "fmt"

func main() {
     marks := 30
     if marks >= 35 {     
        fmt.Println("Congratulations you have passed exam..!!)
     }
}

Run in playground

When we save and run this code, we will receive no output because the condition was not met and we did not tell the program to execute another statement.

if else statement

It is likely that we will want the program to do something even when an if statement evaluates to false. In the above example, we will want output whether the grade is pass or fail.

To do this, we will add an else statement to the grade condition above that is constructed like this:

package main

import "fmt"

func main() {
     marks := 30
     if marks >= 35 {
        fmt.Println("Congratulations you have passed.!!") 
     } else {
        fmt.Println("Sorry you have failed.!!") 
     }
}

Output

Sorry you have failed.!!

Run in playground

Since the grade variable has the value of 30, the if statement evaluates as false, so the program will not print out Congratulations you have passed.!!. The else statement that follows tells the program to do something anyway.

if else if Statements

So far, we have presented a Boolean option for conditional statements, with each if statement evaluating to either true or false. In many cases, we will want a program that evaluates more than two possible outcomes.

For this, we will use an else if statement, which is written in Go as else if. The else if or else if statement looks like the if statement and will evaluate another condition.

In the bank account program, we may want to have three discrete outputs for three different situations:

  • The balance is below 0
  • balance is equal to 0
  • balance is above 0
package main

import "fmt"

func main() {
     balance := 5500
     if balance < 0 {
        fmt.Println("Your balance is below 0, add funds now or you will be charged a penalty.")
     } else if balance == 0 {
        fmt.Println("Your balance is equal to 0, add funds soon.")
     } else {
        fmt.Println("Your balance is ", balance)
     }
 }

Output

Your balance is  5500

Run in playground

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 finds whether the number is even or odd using the above syntax.

package main

import (
    "fmt"
)

func main() {
    if num := 25; num%2 == 0 {
        fmt.Println(num, "is even number")
    } else {
        fmt.Println(num, "is odd number")
    }
}

Output

25 is odd number

Run in playground

In the above program num is initialized in the if statement.

One thing to be noted is that num is available only for access from inside the if and else. i.e. the scope of num is limited to the if else blocks. If we try to access num from outside the if or else, the compiler will complain.

The else statement should start in the same line after the closing curly brace } of the if statement. If not the compiler will give error. Let’s understand this by means of a program.

package main

import (
    "fmt"
)

func main() {
    if num := 25; num%2 == 0 {
        fmt.Println(num, "is even number")
    } 
    else {
        fmt.Println(num, "is odd number")
    }
}

Output

./prog.go:11:2: syntax error: unexpected else, expecting }

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 language.

The reason is because of the way Go inserts semicolons automatically. You can read about the semicolon insertion rule here

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

...
...
if num := 25; num%2 == 0 {
   fmt.Println(num, "is even number")
}; // Here semicolon inserted by Go Compiler
else {
   fmt.Println(num, "is odd number")
}

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 }

Conditional Statements in Go


Scroll to top