Go Conditions


Go Conditions

In the Go programming language, conditions play a crucial role in controlling the flow of execution based on logical expressions. Conditional statements enable programs to make decisions by evaluating conditions and executing specific code blocks accordingly.


Conditional Statements in Go

Go provides three primary conditional constructs:

  • if Statement
  • if-else Statement
  • if-else if-else Ladder

Each of these structures helps in executing different blocks of code based on the evaluation of a given condition.


1. if Statement

The if statement evaluates a condition, and if the condition returns true, the associated block of code gets executed.

Syntax:

if condition {
    // Executes this code when the condition is true.
}

Example:

package main

import "fmt"

func main() {
    num := 10

    if num > 5 {
        fmt.Println("Number is greater than 5")
    }
}

Output:

Number is greater than 5

Here, since num (10) is greater than 5, the condition evaluates to true, and the statement inside the if block executes.


2. if-else Statement

The if-else statement enables the execution of a different code block when the specified condition evaluates to false.

Syntax:

if condition {
    // Executes this code when the condition is true.
} else {
    // Executes this code when the condition is false.
}

Example:

package main

import "fmt"

func main() {
    num := 3

    if num%2 == 0 {
        fmt.Println("Even Number")
    } else {
        fmt.Println("Odd Number")
    }
}

Output:

Odd Number

3. if-else if-else Ladder

Syntax:

if condition1 {
    // Executes this code if condition1 is met.
} else if condition2 {
    // Executes this code if condition2 is met.
} else {
    // Executes this code when none of the conditions are true.
}

Example:

package main

import "fmt"

func main() {
    age := 20

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

Output:

You are an adult

Here, since age is 20, the second condition (age >= 18 && age < 60) evaluates to true, and the corresponding block executes.


Conclusion

Go provides robust conditional constructs with if, if-else, if-else and if-else Ladder statements. Each has its use cases:

  • if for simple decisions.
  • if-else for binary choices.
  • if-else if-else for multiple conditions.

By mastering these statements, developers can write efficient and readable control flow structures in Go programs.

PreviousNext