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! šÆ
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:
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.
The basic structure of an if-else statement in Go is:
if condition {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}You can also create nested if-else statements to create more complex conditions:
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.
Go provides a short syntax for the if-else statements, which can be more concise:
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.
What is the output of the following code?