if-else in Golang

Similar to all other programming languages if-else statements are available in Golang. We can use the if-else statement to execute codes according to our requirements and conditions.

if else in golang

if synatx in Golang

if statements syntax in golang is bellow –

if codintion {
// code block
}

Golang if Example

package main

import "fmt"

func main() {

	n := 10

	if n > 5 {
		fmt.Println("number is greater then 5")
	}

}

Output –

golang if else

If-else syntax in Golang

if - else snyntax in Golang is given bellow.

if condition{
// code
} else{
// code
}

if-else Golang example

package main

import "fmt"

func main() {

	n := 10

	if n > 5 {
		fmt.Println("number is greater then 5")
	} else {
		fmt.Println("number is less then 5")
	}

}

Nested if-else in Golang

We can use nested if-else in Golang. Syntax and example are given below

Nested if-else syntax in Golang

if condition{
// code
} else if condition {
// code
} else if condition {
// code
} else{
//code
}

Nested if-else example in Golang

package main

import "fmt"

func main() {

	n := 27

	if n > 50 {
		fmt.Println("number is greater then 50")
	} else if n > 25 {
		fmt.Println("number is greater then 25")
	} else if n > 10 {
		fmt.Println("Number is greater then 10")
	} else if n > 5 {
		fmt.Println("Number is greater then 5")
	} else {
		fmt.Println("Number is less then 5")
	}

}

Output

nested if else

Similar Golang Tutorials

2 thoughts on “if-else in Golang”

Leave a Comment