Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

if
else
if-else
golang
communitycreator

What is an if-else statement in Golang?

Fareeha Rafaqat

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 else code.

package main // for standalone executables
import "fmt" // implements formatted I/O

func main() { 
   // Defining a variable
   var number int = 10;
   // var number int = 2;
 
   // Writing an "if-condition" to check if 
   // the number is greater than 5 
   if( number > 5 ) { 
      // Print the following if condition is true 
      fmt.Printf("The number is greater than 5\n" );
   } else {
      // Print the following if if-condition is false 
      fmt.Printf("The number is less than 5\n" );
   }
   // Print the value of number    
   fmt.Printf("The value of number is %d\n", number);
}
The "if-else" statement in Golang

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 executables
import "fmt" // implements formatted I/O

func main() { 
   // Your code
}
Using the "if-else" statement to check if a number is even or odd

RELATED TAGS

if
else
if-else
golang
communitycreator
RELATED COURSES

View all Courses

Keep Exploring