Control Flow: if/else (Conditionals & Logical Operators) - Go Tutorial for Beginners #6
Video: Control Flow: if/else (Conditionals & Logical Operators) - Go Tutorial for Beginners #6 by Taught by Celeste AI - AI Coding Coach
Watch full page →Control Flow: if/else (Conditionals & Logical Operators) in Go
In Go, you can control the flow of your program using if, else if, and else statements without needing parentheses around conditions. This tutorial covers basic conditionals, the use of logical operators like &&, ||, and !, and how to declare variables within an if statement for concise code.
Code
package main
import "fmt"
func main() {
age := 20
// Basic if statement (no parentheses needed)
if age >= 18 {
fmt.Println("You are an adult.")
}
// if-else and else-if chain
if age < 13 {
fmt.Println("You are a child.")
} else if age < 18 {
fmt.Println("You are a teenager.")
} else {
fmt.Println("You are an adult.")
}
// Short statement syntax: declare variable in if
if canVote := age >= 18; canVote {
fmt.Println("You can vote.")
} else {
fmt.Println("You cannot vote yet.")
}
// Using logical operators
isStudent := true
if age >= 18 && isStudent {
fmt.Println("You are an adult student.")
}
if !(age >= 65) {
fmt.Println("You are not a senior citizen.")
}
}
Key Points
- Go's if statements do not require parentheses around the condition.
- Use else if and else to handle multiple conditional branches.
- You can declare and initialize variables within an if statement for cleaner code.
- Logical operators && (and), || (or), and ! (not) combine or invert conditions.
- Comparison operators like >, <, >=, <=, ==, and != are used to compare values.