0 votes
in GoLang by
Please provide the example with syntax of If-Else in Golang

1 Answer

0 votes
by

If else is a conditional statement. The synax is

if condition{
// statements_1
}else{
// statements_2
}

Here the condition is evaluated and if it’s true statements_1 will be executed else statements_2 will be executed.

You can use if statement without else also. You also can have chained if else statements. The below programs will explain more about if else.

Execute the below program. It checks if a number, x, is less than 10. If so, it will print “x is less than 10”

package main
import "fmt"

func main() {  
    var x = 50
    if x < 10 {
        //Executes if x < 10
        fmt.Println("x is less than 10")
    } 
}

Here since the value of x is greater than 10, the statement inside if block condition will not executed.

Now see the below program. In this Go programming language tutorial, we have an else block which will get executed on the failure of if evaluation.

package main
import "fmt"

func main() {  
    var x = 50
    if x < 10 {
        //Executes if x is less than 10
        fmt.Println("x is less than 10")
    } else {
        //Executes if x >= 10
        fmt.Println("x is greater than or equals 10")
    }
}

This program will give you output

x is greater than or equals 10

Related questions

0 votes
asked Aug 11, 2022 in GoLang by SakshiSharma
0 votes
0 votes
asked Apr 27, 2023 in GoLang by Robin
...