In this Tutorial -:
Introduction
Conditional statements are an essential part of any programming language, allowing developers to control the flow of their code based on certain conditions.
In Go, the if-else statement enables you to make decisions and execute different blocks of code depending on whether a given condition is true or false.
In this tutorial, we’ll dive into the world of if-else statements in Go, exploring their syntax, usage, and common scenarios where they come in handy.
Prerequisites
Before we begin, ensure you have Go installed on your system. If you haven’t already done so, you can download the latest version of Go from the official website: https://golang.org/dl/ Once installed, verify the installation by opening a terminal or command prompt and running the following command:
go version
If Go is installed correctly, it will display the version number.
The If-Else Statement in Go
The if-else statement in Go follows a simple and familiar syntax:
if condition {
// Code block executed if the condition is true
} else {
// Code block executed if the condition is false
}
Let’s take a look at a practical example of using the if-else statement in Go:
package main
import "fmt"
func main() {
age := 25
if age >= 18 {
fmt.Println("You are an adult.")
} else {
fmt.Println("You are a minor.")
}
}
O/P
You are an adult.
In the above code, we are simply checking if variable ‘age’ is greater than 18 or not. If it is, then we print ‘You are an adult.‘ else it prints ‘You are a minor.‘.
The If Statement with Short Declaration
Go allows you to combine the if statement with the short variable declaration := to declare and initialize a variable right before the condition check.
Here’s an example:
package main
import "fmt"
func main() {
if num := 10; num%2 == 0 {
fmt.Println("The number is even.")
} else {
fmt.Println("The number is odd.")
}
}
O/P
The number is even.
In this example, we declare and initialize the variable num and check if it is even or odd in the same if statement.
Nested If-Else Statements
You can also nest if-else statements to create more complex decision-making structures.
Here’s an example:
package main
import "fmt"
func main() {
num := 42
if num > 0 {
fmt.Println("The number is positive.")
} else if num < 0 {
fmt.Println("The number is negative.")
} else {
fmt.Println("The number is zero.")
}
}
O/P
The number is positive.
In this example, we check if num is positive, negative, or zero and print the corresponding message.
The if-else statement is a powerful tool in Go programming, allowing you to make decisions based on conditions. In this tutorial, we explored the syntax and usage of if-else statements, as well as how to use short declarations with the if statement. We also saw how to nest if-else statements to create more intricate decision structures. By mastering if-else statements, you can add flexibility and control to your Go programs and handle various scenarios effectively.