Fundamentals

Control Statements

Control statements are just instructions that change the direction the computer reads your code.

In Go, there are exactly three tools you need to know to control the flow of your program.

if and else

if lets the computer ask a simple "Yes or No" question.

  • If the answer is "Yes" (True), it runs a specific block of code.
  • If the answer is "No" (False), it skips that block of code.
main.go
package main

import "fmt"

func main() {
    score := 85

    if score >= 90 {
        fmt.Println("Grade: A")
    } else if score >= 75 {
        fmt.Println("Grade: B")
    } else {
        fmt.Println("Grade: C")
    }
}
The else if and else keywords must start on the exact same line as the closing brace } of the previous block.

The "Short Statement" If

Go allows you to declare a variable right before the condition, separated by a semicolon. This keeps your code clean because the variable only exists inside the if block:

// Calculate the total, then immediately check if it's > 100
if total := 50 * 3; total > 100 {
    fmt.Println("You are eligible for free shipping!")
}

for loop

A for loop is used to repeatedly execute a block of code as long as a condition is true.

The designers of Go hated having multiple ways to do the exact same thing. So, they fired the while loop and the do-while loop, and gave all their jobs to the for loop!
for initialization; condition; post {
    // code block
}

Varients of for loop

  • Standard Loop
    for i := 0; i < 5; i++ { }
    
  • While-style Loop
    i := 0
    for i < 5 {
        i++
    }
    
  • The Infinite Loop
    If you just write for { ... } with no conditions, it loops forever.

    We use this all the time in backend engineering for servers that need to constantly listen for incoming web traffic!

switch statement

A switch statement is used to select one block of code from multiple options based on a value or condition.

switch expression {
    case value1:
        // code
    case value2:
        // code
    default:
        // fallback
}
In languages like C or JavaScript, if you forget to write break at the end of a switch case, your code accidentally runs the next case too. Go fixed this. Go automatically breaks.
Copyright © 2026