Go if-else Statements

beginner
9 min

Go if-else Statements

Welcome to our deep dive into the if-else statements in Go! This tutorial is perfect for both beginners and intermediates, so let's get started! šŸŽÆ

Introduction

The if-else statement is a fundamental control structure in Go that allows conditional execution of code. It's used to test conditions and execute different blocks of code based on the outcome. Let's dive into a simple example:

go
package main import "fmt" func main() { age := 18 if age >= 18 { fmt.Println("You are eligible to vote.") } else { fmt.Println("You are not eligible to vote.") } }

šŸ“ Note: In this example, we are checking if the age variable is greater than or equal to 18. If true, the message "You are eligible to vote." is printed. If false, the message "You are not eligible to vote." is printed.

Basic if-else Structure

The basic structure of an if-else statement in Go is:

go
if condition { // Code to execute if condition is true } else { // Code to execute if condition is false }

Nested if-else Statements

You can also create nested if-else statements to create more complex conditions:

go
package main import "fmt" func main() { grade := 'C' if grade == 'A' { fmt.Println("Excellent! You got an A.") } else if grade == 'B' { fmt.Println("Great job! You got a B.") } else if grade == 'C' { fmt.Println("Good effort! You got a C.") } else { fmt.Println("Keep practicing! You need to improve.") } }

šŸ“ Note: In this example, we have nested if-else statements to check the grade of a student. Based on the grade, different messages are printed.

Short if-else Syntax (Go 1.16 and later)

Go provides a short syntax for the if-else statements, which can be more concise:

go
package main import "fmt" func main() { grade := 'C' if grade == 'A' { fmt.Println("Excellent! You got an A.") } else if grade == 'B' { fmt.Println("Great job! You got a B.") } else if grade == 'C' { fmt.Println("Good effort! You got a C.") } else { fmt.Println("Keep practicing! You need to improve.") } // Using the short if syntax if grade == 'A' { fmt.Println("Excellent! You got an A.") } else if grade == 'B' { fmt.Println("Great job! You got a B.") } else if grade == 'C' { fmt.Println("Good effort! You got a C.") } }

šŸ“ Note: In this example, we have shown both the long and short syntaxes for the if-else statements. The short syntax makes the code more concise.

Quiz

Quick Quiz
Question 1 of 1

What is the output of the following code?