Go If-Else Statement

Go If Else Statement is used to conditionally execute either of the two code blocks, based on the result of a condition or boolean expression.

In this tutorial, we will learn the syntax of Go If Else statement, its syntax and usage with examples.

Syntax

The syntax of Go If Else statement is

</>
Copy
 if condition {
     //code
 } else {
     //code
 }

where the condition is a boolean expression or would return a boolean value.

If the condition evaluates to true, the code inside if-block executes. If the expression evaluates to false, the code inside the else-block executes.

Examples

In the following example, we will write an if-else statement with the condition that a is less than b.

example.go

</>
Copy
package main

import "fmt"

func main() {
	var a int = 5
	var b int = 20
 
	if a < b {
		fmt.Println("a is less than b")
	} else {
		fmt.Println("a is not less than b")
	}
}

Since, the value is a is less than that of b, the code in if-block executes.

Output

a is less than b

Now, let us take the values in a and b, such that a is not less than b, and observe the output.

example.go

</>
Copy
package main

import "fmt"

func main() {
	var a int = 36
	var b int = 20

	if a < b {
		fmt.Println("a is less than b")
	} else {
		fmt.Println("a is not less than b")
	}
}

Since, the value is a is not less than that of b, the code in else-block executes.

Output

a is not less than b

Go If Else If

We can extend an if-else statement to check multiple conditions in a ladder and execute the corresponding block of code where the condition becomes true.

The syntax of Go If-Else-If statement is:

</>
Copy
 if condition_1{
     //code
 } else if condition_2 {
     //code
 } else if condition_3 {
     //code
 } else {
     //code
 }

where the condition is a boolean expression or would return a boolean value.

The execution falls from top to bottom, and when a condition evaluates to true, then the corresponding code block executes, and the execution comes out of this if-else-if ladder. If no condition is true, then the else-block code executes.

Example

In the following example, we will write an if-else-if statement.

example.go

</>
Copy
package main  

import "fmt"  

func main() { 
	var a int = 20
	var b int = 20
 
	if(a<b){
		fmt.Println("a is less than b")
	} else if(a==b) {
		fmt.Println("a is equal to b")
	} else {
		fmt.Println("a is greater to b")
	}
}

Output

a is equal to b

Conclusion

In this Golang Tutorial, we learned about Go If-Else statement and Go If-Else-If, their syntax and usage with example programs.