Conditional Statements

Conditional statements allow you to execute different blocks of code based on certain conditions. Go provides several types of conditional statements: if, else if, else, and switch.

The if Statement

The simplest form of a conditional statement is the if statement. It evaluates a condition and executes the associated block of code if the condition is true.

package main

import "fmt"

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

The else if and else Statements

You can extend an if statement with else if and else to handle multiple conditions.

package main

import "fmt"

func main() {
    age := 16

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

The switch Statement

The switch statement is a cleaner way to handle multiple conditions without nested if statements. It evaluates an expression and executes the corresponding case.

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("Another day")
    }
}

Comparison of Conditional Statements

Statement TypeSyntax ExampleUse Case
ifif condition { ... }For single condition checks
else ifelse if condition { ... }For multiple conditions
elseelse { ... }For a fallback case
switchswitch expression { ... }For multiple discrete cases

Looping Constructs

Loops are used to execute a block of code repeatedly. Go provides two primary looping constructs: for and range.

The for Loop

The for loop is the only loop construct in Go. It can be used in several ways: as a traditional loop, a condition-based loop, or an infinite loop.

Traditional for Loop

package main

import "fmt"

func main() {
    for i := 0; i < 5; i++ {
        fmt.Println(i)
    }
}

Condition-Based for Loop

You can also use a for loop with a condition, similar to a while loop in other languages.

package main

import "fmt"

func main() {
    i := 0
    for i < 5 {
        fmt.Println(i)
        i++
    }
}

Infinite for Loop

To create an infinite loop, omit the loop condition entirely.

package main

import "fmt"

func main() {
    i := 0
    for {
        if i >= 5 {
            break
        }
        fmt.Println(i)
        i++
    }
}

The range Loop

The range keyword is used to iterate over elements in a variety of data structures, such as arrays, slices, maps, and strings.

Iterating Over a Slice

package main

import "fmt"

func main() {
    fruits := []string{"apple", "banana", "cherry"}

    for index, fruit := range fruits {
        fmt.Printf("Index: %d, Fruit: %s\n", index, fruit)
    }
}

Iterating Over a Map

package main

import "fmt"

func main() {
    scores := map[string]int{"Alice": 90, "Bob": 85, "Charlie": 92}

    for name, score := range scores {
        fmt.Printf("%s scored %d\n", name, score)
    }
}

Comparison of Looping Constructs

Loop TypeSyntax ExampleUse Case
forfor i := 0; i < n; i++ { ... }For a fixed number of iterations
Condition-basedfor condition { ... }For iterating until a condition is met
Infinitefor { ... }For an ongoing process until a break
rangefor index, value := range collection { ... }For iterating over collections

Best Practices

  1. Keep Conditions Simple: When using if statements, ensure that conditions are straightforward to enhance readability.
  2. Use switch for Clarity: Prefer switch statements over multiple if statements when dealing with multiple discrete values.
  3. Avoid Infinite Loops: Use infinite loops judiciously. Always ensure there is a clear exit condition to prevent unintentional infinite execution.
  4. Leverage range: Utilize the range keyword for iterating over collections to improve readability and reduce boilerplate code.

By mastering control structures in Go, you can write clear and efficient code that effectively handles various programming scenarios.

Learn more with useful resources