Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Introduction to Control Structures in Go Programming

What are Control Structures?

Control structures are fundamental elements in programming that allow you to control the flow of execution of your code. They enable you to make decisions, repeat actions, and perform different operations based on certain conditions. In Go programming, the primary control structures are:

  • Conditional Statements (if-else)
  • Switch Statements
  • Loops (for)

Conditional Statements (if-else)

Conditional statements allow your program to execute certain pieces of code based on whether a condition is true or false. In Go, the if-else statement is used for this purpose.

Syntax:

if condition {
    // code to execute if condition is true
} else {
    // code to execute if condition is false
}

Example:

package main

import "fmt"

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

Switch Statements

The switch statement in Go provides an elegant way to perform different actions based on the value of a variable or expression. It can be seen as a cleaner alternative to multiple if-else statements.

Syntax:

switch expression {
case value1:
    // code to execute if expression == value1
case value2:
    // code to execute if expression == value2
default:
    // code to execute if expression does not match any case
}

Example:

package main

import "fmt"

func main() {
    day := "Monday"
    switch day {
    case "Monday":
        fmt.Println("Start of the work week.")
    case "Friday":
        fmt.Println("Last work day of the week.")
    default:
        fmt.Println("It's just another day.")
    }
}
Output:
Start of the work week.

Loops (for)

Loops allow you to repeat a block of code multiple times. In Go, the for loop is the only looping construct, but it can be used in different ways to achieve various looping behaviors.

Basic Syntax:

for initialization; condition; post {
    // code to execute
}

Example:

package main

import "fmt"

func main() {
    for i := 0; i < 5; i++ {
        fmt.Println(i)
    }
}
Output:
0
1
2
3
4

Using for as a while loop:

package main

import "fmt"

func main() {
    i := 0
    for i < 5 {
        fmt.Println(i)
        i++
    }
}
Output:
0
1
2
3
4

Infinite loop:

package main

import "fmt"

func main() {
    for {
        fmt.Println("Infinite loop")
        break // To prevent actual infinite loop in this example
    }
}
Output:
Infinite loop