Go If-Else Statements: Conditional Control Flow

The if statement is a fundamental control flow structure in Go, allowing you to execute different code blocks based on conditions.



Basic If Statement

The simplest form of the if statement checks a boolean condition and executes the code block if the condition is true.

Syntax
if condition {
  // code to be executed if condition is true
}
Output
None

If-Else Statement

The else clause provides an alternative code block to be executed when the if condition is false.

Syntax
if condition {
  // code to be executed if condition is true
} else {
  // code to be executed if condition is false
}
Output
None

If-Else If Chain

For multiple conditions, use else if statements. Only the first true condition's block will be executed.

Syntax
if condition1 {
  // code for condition1
} else if condition2 {
  // code for condition2
} else if condition3 {
  // code for condition3
} else {
  // default code if no conditions are true
}
Output
None

Short Declaration in If Statements

You can declare variables within the if condition, and they're accessible within the if and else blocks.

Syntax
if x := someFunction(); x > 0 {
  // use x here
} else {
  // use x here
}
Output
None

Nested If Statements

You can nest if statements for complex logic, but use them carefully to avoid making code hard to read.

Syntax
if outerCondition {
  if innerCondition {
    // code
  } else {
    // code
  }
}
Output
None

Example: Determining a Number's Range

Syntax
package main

import "fmt"

func main() {
  num := 42

  if num < 0 {
    fmt.Println("Negative")
  } else if num <= 10 {
    fmt.Println("Small positive")
  } else {
    fmt.Println("Large positive")
  }
}
Output
Large positive

Key Points

  • Conditions must evaluate to boolean values.
  • Braces are required for code blocks.
  • Indentation improves readability.
  • Consider using switch statements for multiple comparisons on the same value.

By mastering if-else statements, you'll be able to create flexible and responsive Go programs.