Back to blog
Sep 04, 2024
5 min read

Mastering Control Structures in Go: Conditionals, Loops and Beyond

Learn about if-else switch conditionals and for loops

Hello devs! Let`s talk about control structures.

Control structures are the backbone of any programming language. They dictate the flow of our application, allowing you to make decisions and perform repetitive tasks. In this post, we’ll dive deep into the control structures in Go, exploring how to use if/else, switch, and for loops effectively.

Understanding if/else statements

The if/else statement is a fundamental control structure that lets you execute blocks of code based on certain conditions. In Go the syntas is straightforward and easy to follow.

Basic if Statement:

  x := 18
  if x > 12 {
    fmt.Println("x is greater than 12")
  }

Here if x variable is greater than 12, the message is printed. Yeah, it’s too simple, right?

Adding else:

  x := 18
  if x > 12 {
    fmt.Println("x is greater than 12")
  } else {
    fmt.Println("x is 12 or less")
  }

Adding else to your code you can handle two outcomes.

Handling Multiple Conditions with else if:

x := 5
if x > 10 {
  fmt.Println("x is greater than 10")
} else if  x > 4 {
  fmt.Println("x is greater than 4 but less than or equal to 10")
} else {
  fmt.Println("x is 4 or less")
}

Chaining else if statements allow you to handle multiple conditions in a clear and concise manner.

Powering Up with switch Statements

While if/else chains are useful, they can become unwieldy with numerous conditions. Enter the switch statement - a cleaner and more efficient way to handle multiple possible values.

Basic switch Usage:

weekDay := "Thursday"

switch weekDay {
case "Monday":
  fmt.Println("Start of the workweek!")
case "Wednesday":
  fmt.Println("Midweek!")
case "Friday":
  fmt.Println("Almost the weekend!")
default:
  fmt.Println("Just another day!")
}

In this example, the switch statement evaluates the value of day and matches it to one of the case blocks. The default block catches any unmatched cases. If you are a skilled programmer from another language like Java, C++, PHP etc, you may ask me where is the break statement? Well, in Go if one switch case is matched then the next cases won’t be evaluated (this makes more sense to me) and the code flow will continue after the switch.

Combining Multiple Caases:

day := "Saturday"

switch day {
case "Saturday", "Sunday":
  fmt.Println("It's the weekend!")
default:
  fmt.Println("It's a weekday.")
}

You can combine multiple case expressions into a single block, making your code even more concise.

Switch Without an Expression:

age := 20
switch {
  case age < 18:
    fmt.Println("You are a minor.")
  case age >= 18 && age < 60:
    fmt.Println("You are an adult.")
  default:
    fmt.Println("You are a senior.")
}

A switch without an expression is a powerful alternative to complex if/else if chains, and improves readability.

Mastering Loops in Go

Unlike other languages, Go has just one looping statement: the for loop. However this single statement in incredibly versatile.

The Classic for Loop:

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

This is your classic for loop, where i increments from 0 to 4, printing each value.

Replicating while statement with for:

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

By omitting the initialization and post statements, you effectively create a while loop in Go

Beware the Infinite Loop:

for {
  fmt.Println("This will run forever and ever and ever")
}

Omitting all three components of the for loop results in an infinite loop. Use this with caution!

Iterating Over Collections with range:

nums := []int{2, 4, 6, 8}
for k, v := range nums {
  fmt.Printf("Key: %d, Value: %d\n", k, v)
}

The range keyword is your go-to for iterating over slices, arrays, maps, and strings, providing both index and value.

Fine-Tuning Loops with break and continue

To manage your loop flow more precisely, Go offers the break and continue statements.

Exiting Early with break:

for i := 0; i < 10; i++ {
  if i == 5 {
    break
  }
  fmt.Println(i)
}

The break statement exits the loop as soon as i equals 5

Skipping Iterations with continue

for i := 0; i < 10; i++ {
  if i % 2 == 0 {
    continue
  }
  fmt.Println(i)
}

Here, continue skips the current iteration when i is even, printing only odd numbers.

Wrapping Up

Go’s control structures are designed for simplicity and clarity. Whether you’re branching logic with if/else, handling multiple conditions with switch, or iterating with for, Go provides the tools to write clean and efficient code.

Test your skills?

What do you think to test what you learned in this post? Try writing a simple calculator that takes two numbers and an operator (+, -, *, /) from the user and performs the corresponding operation. Or, challenge yourself by printing the first 10 numbers in the Fibonacci sequence using a for loop.


Mastering these control structures is a crucial step in becoming proficient in Go. Stay tuned for the next post, where we’ll dive into functions and error handling, two more pillars of writing robust Go code.