Go if..else, if..else..if, nested if with Best Practices


GO

Reviewer: Deepak Prasad

Introduction

In computer programming, conditional statements help you make decisions based on a given condition. The conditional statement evaluates if a condition is true or false, therefore it is worth noting that if statements work with boolean values. Just like other programming languages, Go has its own construct for conditional statements. In this tutorial , we will learn about different types of conditional statements in Go.

Below are the topics that we will cover

  • If statement
  • If - Else statement
  • If -else if else statement
  • Nested If statement
  • Logical operators AND , OR and NOT
  • Using multiple conditions if if else

 

Supported Comparison Operators in GO

Before we go ahead learning about golang if else statement, let us be familiar with supported comparison operators as you may need to use them in the if else conditions for decision making:

Operator Description Example
== Equal to num == 0
!= Not equal to num != 0
< Less than num < 0
<= Less than or equal to num <= 0
> Greater than num > 0
>= Greater than or equal to num >= 0

 

if statement

If a statement is used to specify  a block of code that should be executed if  a certain condition is true.

Syntax 

if condition {
   code to execute
}

Explanation

In the above syntax, the keyword if is used to declare the beginning of an if statement, followed by a condition that is being tested. The condition should be a value of boolean type, the the block of code between opening and closing curly brackets will be executed only if the condition is true. In the next example, we define code that will only run if age is above 18 years.

Example

package main
 
import "fmt"
 
func main() {
   age := 19
   ageLimit := 18
   if age > ageLimit {
       fmt.Println("You are allowed to drive a car")
   }
}

Explanation

In the preceding example, we define the age and ageLimit variables. In the if statement we compare the value of age and ageLimit by checking which is greater. The statement age > ageLimit will evaluate to true because 19 is greater than 18. The code block will be executed because the condition is true.

Output

$ go run main.go
You are allowed to drive a car

 

One liner if statement

We can also convert our if condition to run in one line, for example here I have written the same if condition in 2 different ways, one is multi line while the other is using single line:

package main

import "fmt"

func main() {
	num0 := 150
	
	// multi-line if condition
	if num0 > 100 || num0 < 900 {
		fmt.Println("Currency: ", num0)
	}
	
 	// one liner if condition
	if num0 > 100 || num0 < 900 {fmt.Println("Currency: ", num0)}
}

Output:

$ go run main.go
Currency: 150
Currency: 150

 

if else Statement

If Else statement is used to evaluate both conditions that might be true or false. In the previous example, we did not really care if a condition evaluates to false. We use If Else conditional statements to handle both true and false outcomes.

Example

package main
 
import "fmt"
 
func main() {
   age := 12
   ageLimit := 18
 
   if age > ageLimit {
       fmt.Println("You are allowed to drive a car")
   } else {
       fmt.Println("You are NOT allowed to drive a car")
   }
}

Explanation

In the preceding example, we define the age and ageLimit variables. In the if statement we compare the value of age and ageLimit by checking which is greater. The statement age > ageLimit will evaluate to false because 12 is less than 18. The second code block will be executed because the condition is false.

Output

$ go run main.go
You are NOT allowed to drive a car

 

if else if statement

If Else If statement is used to specify a new condition if the first condition is false. When using If Else If statement, you can nest as many If Else conditions as you desire.

Example

package main
 
import "fmt"
 
func main() {
   age := 17
   ageLimit := 18
 
   if age > ageLimit {
       fmt.Println("You are allowed to drive a car")
   } else if age == 17 {
       fmt.Println("Prepare to get a driving license")
   }else{
       fmt.Println("You are NOT allowed to drive a car")
   }
}

Explanation

In the above example, the first if statement evaluates to false because age (17) is not greater than ageLimit(18). We then check again if age is equal to 17, which evaluates to true. The block of code inside this section will be executed.

Output

$ go run main.go
Prepare to get a driving license

 

Nested if Statement

Nested if Statement, is a If conditional statement that has an If statement inside another If statement. The nested If statement will always be executed only if the outer If statement evaluates to true.

Syntax

if conditionX {
   if conditionY {
   }
}

In the above syntax, the second if statement with condition labeled conditionY is housed inside the outer If statement with condition labeled conditionX. As long as condition labeled conditionX is true , if conditionY will be executed.

Example

package main
 
import "fmt"
 
func main() {
   serverPort := 8000
   var clientPort int
   if serverPort  == 8000 {
       clientPort = 8001
       if clientPort > 7900 {
           fmt.Printf("Server running on http://127.0.0.1:%d \n", serverPort)
           fmt.Printf("Server running on http://127.0.0.1:%d \n", clientPort)
       }
   }
}

Output

$ go run main.go
Server running on http://127.0.0.1:8000
Server running on http://127.0.0.1:8001

 

Supported Logical Operators in GO

We also have some logical operators on golang which help us when we have to check for multiple conditions:

Operator Description Example
== Equal to num == 0
!= Not equal to num != 0
< Less than num < 0
<= Less than or equal to num <= 0
> Greater than num > 0
>= Greater than or equal to num >= 0

 

if else statements using logical operator

In Go we use logical operators together with If conditional statements to achieve certain goals in our code. Logical operators return/execute to boolean values, hence making more sense using them conditional statements. Below are definitions of the three logical operators in Go.

 

Using logical AND operator

Checks of both operands are none zero. In case both operands are none-zero, a true value will be returned, else a false value will be returned. The operator representing logical AND is &&.

Example

package main
 
import (
   "fmt"
)
func main() {
   isClient := true
   isLoggedIn := true
 
   if isClient && isLoggedIn {
       fmt.Println("Client is logged in")
   }
}

Output

$ go run main.go
Client is logged in

 

Using logical OR operator

Check if one operand is true. In case one operand is true code will be executed. The operator representing logical OR is || .

Example

package main
 
import (
   "fmt"
)
 
func main() {
   isClient := true
   isLoggedIn := false
 
   if isClient || isLoggedIn {
       fmt.Println("Current user is a Client")
   }
}

 

Using logical NOT operator

Reverses the logical state of its operands. If a condition is  true, the logical operator NOT will change it to false. The operator representing logical Not is ! .

Example

package main
 
import (
   "fmt"
)
 
func main() {
   isClient := true
   isLoggedIn := false
 
   if !(isClient && isLoggedIn) {
       fmt.Println("Current user is a Client  and is not logged in")
   }
}

Output

$ go run main.go
Current user is a Client  and is not logged in

 

Using multiple condition in golang if else statements

We can also add multiple conditional blocks inside the if else statements to further enhance the decision making. Let us check some more examples covering if else multiple condition:

 

if statement with 2 logical OR Operator

Here we are checking if our num is more than 100 or less than 900:

package main

import "fmt"

func main() {
	num0 := 150
	if num0 > 100 || num0 < 900 {
		fmt.Println("num0 is greater than 100 and less than 900")
	}
}

Output:

$ go run main.go
num0 is greater than 100 and less than 900

 

if statement with 3 logical OR Operator

In this example we add one more OR condition to the if condition:

package main

import "fmt"

func main() {
	num0 := 150
	if num0 > 100 || num0 < 900 || num0 != 0 {
		fmt.Println("num0 is non-empty or greater than 100 and less than 900")
	}
}

Output:

$ go run main.go
num0 is non-empty or greater than 100 and less than 900

 

Using both logical AND and OR operator in single if statement

We can also use both AND and OR operator inside a single if statement, here is an example:

package main

import "fmt"

func main() {
	num0 := 150
	if num0 > 100 || num0 < 900 && num0 != 0 {
		fmt.Println("num0 is non-empty or greater than 100 and less than 900")
	}
}

Output:

$ go run main.go
num0 is non-empty or greater than 100 and less than 900

 

Using multiple conditions with if..else..if..else statement

Now we have used multiple conditions in our if condition but you can use the same inside else..if condition or combine it with if..else..if statements.

package main

import "fmt"

func main() {
	num0 := 1100
	if num0 > 100 && num0 < 900 {
		fmt.Println("num0 is non-empty or greater than 100 and less than 900")
	} else if num0 >= 900 && num0 < 1000 {
		fmt.Println("num0 is definitely more than 900 and less than 1000")
	} else {
		fmt.Println("num0 seems to be higher than 1000")
	}
}

Output:

$ go run main.go
num0 seems to be higher than 1000

 

Summary

In Go, we use conditional statements  to handle decisions precisely in code. They enable our code to perform different computations or actions depending on whether a condition is true or false. In this article we have learned about different if conditional statements like If, If Else, If Else If Else, Nested If statements

 

References

https://go.dev/tour/flowcontrol
https://www.golangprograms.com/golang-if-else-statements.html

 

Related Keywords: golang if else shorthand, golang if else one line, golang if else multiple conditions, golang if else string, golang if true, golang if else best practices, golang if statement with assignment, golang if not

 

Antony Shikubu

Antony Shikubu

He is highly skilled software developer with expertise in Python, Golang, and AWS cloud services. Skilled in building scalable solutions, he specializes in Django, Flask, Pandas, and NumPy for web apps and data processing, ensuring robust and maintainable code for diverse projects. You can reach out to him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment