Go if with Short Statement 🎯

beginner
19 min

Go if with Short Statement 🎯

Welcome to our comprehensive guide on the if statement in Golang! This tutorial is designed for beginners and intermediates who are eager to learn and master this essential programming concept. Let's dive right in!

What is an if Statement? 📝

The if statement in Golang is a control structure that allows your code to make decisions and execute different blocks of code based on a given condition. It's like a traffic light: if the condition is true, the code will move forward; if it's false, it will wait.

Syntax and Structure 💡

The basic syntax of an if statement in Golang is as follows:

go
if condition { // Code to be executed if the condition is true }

Let's take a look at a simple example:

go
package main import "fmt" func main() { age := 20 if age >= 18 { fmt.Println("You are an adult.") } }

In this example, we define an integer variable age and assign it the value 20. Then, we use an if statement to check if the age is greater than or equal to 18. If the condition is true, the program prints "You are an adult."

Short if Statement 💡

Go allows a shortened syntax for a single statement if block:

go
if condition { // Single statement to be executed if the condition is true }

This can be very useful for improving code readability and reducing redundancy. Here's an example:

go
package main import "fmt" func main() { age := 20 if age >= 18 { fmt.Println("You are an adult.") } if age < 18 { fmt.Println("You are a minor.") } // Short `if` statement if score > 90 { grade := "A" } }

In the short if example, we only have one statement inside the block (assigning the grade variable). Since we only have one statement, we can use the short if syntax, which executes the assignment if the condition is true and skips it otherwise.

Else Clause 📝

The else clause in Golang is used to specify a block of code to be executed when the condition in the if statement is false. Here's an example:

go
package main import "fmt" func main() { age := 16 if age >= 18 { fmt.Println("You are an adult.") } else { fmt.Println("You are a minor.") } }

In this example, we check if the age is greater than or equal to 18. If the condition is true, we print "You are an adult." If it's false, we print "You are a minor."

Else If Clause 📝

The else if clause in Golang is used to check multiple conditions. Here's an example:

go
package main import "fmt" func main() { score := 85 if score >= 90 { grade := "A" } else if score >= 80 { grade := "B" } else if score >= 70 { grade := "C" } else { grade := "F" } fmt.Println(grade) }

In this example, we check if the score is greater than or equal to 90, 80, and 70, respectively. If none of the conditions are true, we assume the score is an "F."

Quiz 🎯

Quick Quiz
Question 1 of 1

In the following code snippet, what will be the output?