Control Structures

Part of Golang Mastery course

~15 min read
Interactive
Hands-on
Beginner-friendly

Control Structures in Go

Control structures direct the flow of your program's execution. Go provides simple, clean control structures to handle conditionals, loops, and switching between different execution paths.

Conditional Statements#

If Statement#

The basic if statement in Go looks like this:

example.go
if condition {
string">"comment">// code to execute if condition is true
}
 

Notice that Go doesn't require parentheses around the condition, but the braces {} are mandatory.

If-Else Statement#

You can add an else clause to handle the case when the condition is false:

example.go
if condition {
string">"comment">// code to execute if condition is true
} else {
string">"comment">// code to execute if condition is false
}
 

If with Multiple Conditions#

For multiple conditions, use else if:

example.go
if condition1 {
string">"comment">// code for condition1
} else if condition2 {
string">"comment">// code for condition2
} else {
string">"comment">// code for all other cases
}
 

If with a Short Statement#

Go allows you to execute a short statement before the condition:

example.go
if x := getValue(); x > 10 {
fmt.Println(string">"x is greater than 10")
} else {
fmt.Println(string">"x is less than or equal to 10")
}
 

In this example, x is scoped to the if and else blocks only.

Loops#

Go has only one looping construct: the for loop. However, it's versatile and can be used in several ways.

Standard For Loop#

The standard for loop has three components: init statement, condition, and post statement:

example.go
for i := 0; i < 10; i++ {
fmt.Println(i)
}
 

For Loop as a While Loop#

If you skip the init and post statements, you get a while-like loop:

example.go
count := 0
for count < 5 {
fmt.Println(count)
count++
}
 

Infinite Loop#

An infinite loop is created by omitting the condition:

example.go
for {
fmt.Println(string">"Forever!")
string">"comment">// Need a break statement or return to exit
break
}
 

For Loop with Range#

The range form of the for loop iterates over elements in collections like arrays, slices, strings, maps, and channels:

example.go
string">"comment">// Iterating over a slice
numbers := []int{1, 2, 3, 4, 5}
for index, value := range numbers {
fmt.Printf(string">"Index: %d, Value: %d\n", index, value)
}
 
string">"comment">// Iterating over a map
colors := map[string]string{string">"red": string">"#ff0000", string">"green": string">"#00ff00"}
for key, value := range colors {
fmt.Printf(string">"Key: %s, Value: %s\n", key, value)
}
 

Break and Continue#

Use break to exit a loop and continue to skip to the next iteration:

example.go
for i := 0; i < 10; i++ {
if i == 3 {
continue string">"comment">// Skip the rest of this iteration
}
if i == 8 {
break string">"comment">// Exit the loop completely
}
fmt.Println(i)
}
 

Switch Statement#

The switch statement provides a cleaner way to write multiple if-else statements:

example.go
switch day {
case string">"Monday":
fmt.Println(string">"Start of work week")
case string">"Friday":
fmt.Println(string">"End of work week")
case string">"Saturday", string">"Sunday": string">"comment">// Multiple cases
fmt.Println(string">"Weekend!")
default:
fmt.Println(string">"Midweek")
}
 

Switch with No Expression#

A switch without an expression is equivalent to switch true:

example.go
switch {
case time.Hour < 12:
fmt.Println(string">"Good morning!")
case time.Hour < 17:
fmt.Println(string">"Good afternoon!")
default:
fmt.Println(string">"Good evening!")
}
 

Fallthrough#

In Go, each case breaks automatically. To execute the next case, use the fallthrough keyword:

example.go
switch num := 1; num {
case 1:
fmt.Println(string">"One")
fallthrough
case 2:
fmt.Println(string">"Less than three")
case 3:
fmt.Println(string">"Three or less")
}
 

This will print "One" and "Less than three".

Example: Combining Control Structures#

Here's a complete example combining different control structures:

example.go
package main
 
import string">"fmt"
 
func main() {
string">"comment">// Using a for loop with an if statement
for i := 1; i <= 20; i++ {
if i%2 == 0 {
fmt.Printf(string">"%d is even\n", i)
} else {
fmt.Printf(string">"%d is odd\n", i)
}
string">"comment">// Using a switch statement
switch {
case i%3 == 0 && i%5 == 0:
fmt.Println(string">" FizzBuzz")
case i%3 == 0:
fmt.Println(string">" Fizz")
case i%5 == 0:
fmt.Println(string">" Buzz")
}
}
}
 

Exercise#

  1. Write a program that uses if statements to categorize numbers as positive, negative, or zero
  2. Create a loop that prints only the even numbers from 1 to 20
  3. Implement a simple FizzBuzz program using a switch statement

In the next module, we'll explore functions in Go.

Your Progress

33 of 103 modules
32%
Started32% Complete
Previous
SpaceComplete
Next