GO Tutorial



CONDITIONAL STATEMENTS


Conditional Statements in Go

Conditional statements allow your Go programs to make decisions and execute code blocks based on conditions.

if Statement

The most basic conditional statement is if. It executes a block of code only if a specified condition is true.

if condition {
    // code to execute when condition is true
}
  

Example:

age := 18
if age >= 18 {
    fmt.Println("You are an adult.")
}
  

if-else Statement

Use else to execute code when the if condition is false.

if age >= 18 {
    fmt.Println("You are an adult.")
} else {
    fmt.Println("You are a minor.")
}
  

else if Statement

Use else if to check multiple conditions in sequence.

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

Using Short Statement with if

Go allows an optional short statement to execute before the condition in an if. Variables declared in this statement are scoped to the if block.

if err := someFunction(); err != nil {
    fmt.Println("Error occurred:", err)
} else {
    fmt.Println("Success")
}
  

switch Statement

The switch statement is a clean way to select one of many code blocks to execute.

day := 3

switch day {
case 1:
    fmt.Println("Monday")
case 2:
    fmt.Println("Tuesday")
case 3:
    fmt.Println("Wednesday")
default:
    fmt.Println("Invalid day")
}
  

Key Points

  • No need for parentheses () around conditions.
  • Curly braces {} are mandatory.
  • In switch, cases do not fall through by default. Use fallthrough to continue.
Summary: Conditional statements let your program respond to different situations by executing code selectively. Use if for simple conditions, if-else for two-way decisions, else if for multiple choices, and switch for clearer multi-case logic.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review