GO

Go Fundamentals

18 lessons

Progress0%
1. Introduction to Go
1What is Go?
2. Variables and Data Types
1Data Types in Go
3. Control Flow
If, For, and SwitchDefer, Panic, Recover
4. Functions
Function BasicsError Handling
5. Structs and Methods
StructsMethods and Interfaces
6. Concurrency
Goroutines and ChannelsSelect and Sync
7. Maps & Slices Advanced
Slices Deep DiveMaps Operations & Patterns
8. Interfaces Deep Dive
Interface Composition & anyCommon Interfaces & Patterns
9. Packages & Modules
Package SystemGo Modules & Workspace
10. Testing & Standard Library
Testing in GoStandard Library Essentials
All Tutorials
GoControl Flow
Lesson 3 of 18 min
Chapter 3 · Lesson 1

If, For, and Switch

Control Flow in Go

Go keeps control flow simple: there is only one loop keyword, and if/switch have helpful extras.

if with init statement Go's if can run a short statement before the condition. Variables declared there are scoped to the if/else block:

go
if err := doWork(); err != nil {
    log.Fatal(err)
}

Go's only loop: for Go unifies all loop forms with for:

  • Classic: for i := 0; i < 10; i++ { }
  • While-style: for condition { }
  • Infinite: for { }
  • Range: for i, v := range slice { }

range Iterates over arrays, slices, maps, strings (runes), and channels. Returns index and value.

switch Go's switch does not fall through by default. Cases can list multiple values. A switch without a condition behaves like if/else if:

go
switch {
case x < 0: fmt.Println("negative")
case x == 0: fmt.Println("zero")
default: fmt.Println("positive")
}

Key points:

  • No parentheses around conditions in if/for/switch.
  • Use fallthrough to explicitly fall through in switch.
  • break exits a loop; continue skips to the next iteration.

Code Examples

if with init and for rangego
package main

import (
	"fmt"
	"strconv"
)

func main() {
	// if with init statement
	inputs := []string{"42", "abc", "100"}
	for _, s := range inputs {
		if n, err := strconv.Atoi(s); err == nil {
			fmt.Printf("%s -> %d\n", s, n*2)
		} else {
			fmt.Printf("%s -> invalid\n", s)
		}
	}

	// range over map
	scores := map[string]int{"Alice": 95, "Bob": 80}
	for name, score := range scores {
		fmt.Printf("%s: %d\n", name, score)
	}
}

The init statement in if scopes err to the if/else block. range over a map returns key and value in each iteration.

switch without conditiongo
package main

import "fmt"

func classify(n int) string {
	switch {
	case n < 0:
		return "negative"
	case n == 0:
		return "zero"
	case n < 10:
		return "small"
	case n < 100:
		return "medium"
	default:
		return "large"
	}
}

func dayType(day string) string {
	switch day {
	case "Saturday", "Sunday":
		return "weekend"
	default:
		return "weekday"
	}
}

func main() {
	for _, n := range []int{-5, 0, 7, 42, 200} {
		fmt.Printf("%d: %s\n", n, classify(n))
	}
	fmt.Println(dayType("Saturday"))
	fmt.Println(dayType("Monday"))
}

A switch without a condition is like if/else if — cases evaluate boolean expressions. Multiple values in one case use commas.

Quick Quiz

1. How do you write a while-style loop in Go?

2. Does Go's switch fall through by default?

Was this lesson helpful?

PreviousNext