If-else in Golang

Glitch
3 min readMar 16, 2023

--

If-else statements are a fundamental component of programming in Golang. They allow you to execute different blocks of code based on whether a certain condition is true or false. In this blog, we will explore how if-else statements work in Golang and how to use them effectively.

The basic syntax of an if-else statement in Golang is as follows:
if condition {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
The if keyword is followed by a condition that evaluates to either true or false. If the condition is true, the code within the curly braces following the if statement is executed. If the condition is false, the code within the curly braces following the else statement is executed.

Here's an example of an if-else statement in action:
package main

import "fmt"

func main() {
var age int = 18

if age >= 18 {
fmt.Println("You are eligible to vote.")
} else {
fmt.Println("You are not eligible to vote.")
}
}
In this example, we declare a variable called age and assign it the value of 18. We then use an if-else statement to check whether age is greater than or equal to 18. If it is, we print the message "You are eligible to vote." If it's not, we print the message "You are not eligible to vote."

Golang also allows for nested if-else statements, which can be useful in more complex situations. Here's an example:
package main

import "fmt"

func main() {
var num int = 5

if num < 0 {
fmt.Println("Number is negative.")
} else if num > 10 {
fmt.Println("Number is greater than 10.")
} else {
fmt.Println("Number is between 0 and 10.")
}
}
In this example, we check whether num is negative, greater than 10, or between 0 and 10. Depending on the value of num, one of three messages will be printed.

In addition to simple if-else statements, Golang also provides a shorthand notation called the "if statement with a short statement". This notation allows you to declare and assign a variable within the if statement itself. Here's an example:
package main

import "fmt"

func main() {
if num := 10; num > 0 {
fmt.Println("Number is positive.")
} else {
fmt.Println("Number is zero or negative.")
}
}
In this example, we declare and assign the variable num to the value of 10 within the if statement. We then check whether num is greater than 0. If it is, we print the message "Number is positive." If it's not, we print the message "Number is zero or negative."

In conclusion, if-else statements are an essential part of programming in Golang. They allow you to execute different blocks of code based on whether a certain condition is true or false. By using if-else statements effectively, you can write more complex and powerful programs.

--

--

No responses yet