Go Conditions:
Conditional statements are used to perform different actions based on different conditions. Go supports common conditional logic like if, else, and switch.
If Statement
The if statement is used to execute a block of code only if the specified condition is true.
go
package main
import "fmt"
func main() {
age := 20
if age >= 18 {
fmt.Println("You are an adult.")
}
}If-Else Statement
If the condition is false, the code inside the else block is executed.
go
package main
import "fmt"
func main() {
num := 5
if num%2 == 0 {
fmt.Println("Even number")
} else {
fmt.Println("Odd number")
}
}If-Else If-Else Ladder
You can check multiple conditions using else if.
go
package main
import "fmt"
func main() {
score := 75
if score >= 90 {
fmt.Println("Grade A")
} else if score >= 80 {
fmt.Println("Grade B")
} else if score >= 70 {
fmt.Println("Grade C")
} else {
fmt.Println("Grade D")
}
}Switch Statement
Switch is a cleaner way to write multiple conditions that compare the same value.
go
package main
import "fmt"
func main() {
day := 3
switch day {
case 1:
fmt.Println("Monday")
case 2:
fmt.Println("Tuesday")
case 3:
fmt.Println("Wednesday")
default:
fmt.Println("Other day")
}
}