What is an if-else statement in Golang?
If-else
Let’s learn how to use the if-else statement in Golang.
Syntax
The syntax of the if-else statement is:
if (condition) {
// statements to run if the condition is true
} else {
// statements to run if the condition is false
}
Note: The braces around the condition are optional.
Example
Let’s consider the following example. We have an integer number and we compare it with another constant number, 5. In the if statement, we check to see if the number is greater than 5. The code in the else statement runs if it is False. Then, we click the “Run” button to see the code running. The if statement is True in the example given below.
Note: Uncomment line 7 and comment line 6 to run the
elsecode.
package main // for standalone executablesimport "fmt" // implements formatted I/Ofunc main() {// Defining a variablevar number int = 10;// var number int = 2;// Writing an "if-condition" to check if// the number is greater than 5if( number > 5 ) {// Print the following if condition is truefmt.Printf("The number is greater than 5\n" );} else {// Print the following if if-condition is falsefmt.Printf("The number is less than 5\n" );}// Print the value of numberfmt.Printf("The value of number is %d\n", number);}
Output
If the number is 10, the output of the code will be:
The number is greater than 5
The value of number is 10
If the number equals to 2, then the output will be:
The number is less than 5
The value of number is 2
Test yourself
Use the if-else statement to check if a number is even or odd.
package main // for standalone executablesimport "fmt" // implements formatted I/Ofunc main() {// Your code}