</>
Skip to content
Go lessons (12/34)

Go — If Else

Basic if

package main

import "fmt"

func main() {
    temperature := 28

    if temperature > 25 {
        fmt.Println("It's warm outside!")
    }
}

if-else

hour := 14

if hour < 12 {
    fmt.Println("Good morning!")
} else {
    fmt.Println("Good afternoon!")
}

if-else if-else

score := 85

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: F")
}

if with init statement

if num := 42; num > 0 {
    fmt.Println("Positive:", num)
}

switch statement

day := "Monday"

switch day {
case "Monday":
    fmt.Println("Start of week")
case "Friday":
    fmt.Println("Almost weekend")
case "Saturday", "Sunday":
    fmt.Println("Weekend!")
default:
    fmt.Println("Midweek")
}

switch without expression

switch {
case score >= 90:
    grade = "A"
case score >= 80:
    grade = "B"
case score >= 70:
    grade = "C"
default:
    grade = "F"
}

type switch

var i interface{} = "hello"

switch v := i.(type) {
case int:
    fmt.Printf("Integer: %d\n", v)
case string:
    fmt.Printf("String: %s\n", v)
case bool:
    fmt.Printf("Boolean: %t\n", v)
default:
    fmt.Printf("Unknown type: %T\n", v)
}

fallthrough

n := 2

switch n {
case 1:
    fmt.Println("One")
    fallthrough // Falls through to next case
case 2:
    fmt.Println("Two")
    fallthrough
case 3:
    fmt.Println("Three")
}
// Output: Two Three

Combining conditions

age := 25
income := 50000

if age >= 18 && income >= 30000 {
    fmt.Println("Qualifies for premium card")
}

if age < 12 || age > 65 {
    fmt.Println("Discounted ticket")
}

Best practices

  • Use if with init statement for short-lived variables
  • Prefer switch over long if-else if chains
  • Don't use fallthrough unless necessary
  • Go doesn't have a ternary operator — use if-else

Mini Practice

Write Go code that:

  1. Uses if with init statement to check a value
  2. Uses switch to match a day of the week
  3. Uses type switch on an interface{}
  4. Combines conditions with && and ||

Up Next

In the next lesson, you'll learn about Switch — Go's switch statement in depth.

Related Topics

Frequently Asked Questions about If Else

What is If Else in Go?

If Else is a fundamental concept in Go. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn If Else?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn If Else.

Why is If Else important in Go?

If Else is essential for Go development. Understanding this concept will help you write better code and solve real-world problems more effectively.