Go Playbook

Course › Week 1 · Basics and a first CLI › Day 5 · lesson 5 of 42 · 20 min reading + 45–60 min practice

Structs and switch

Your own types: a struct with fields, a slice of structs, a named type with constants, and switch.

structstruct literalsnamed typesiotaswitch

On this page
  1. Structs
  2. A slice of structs
  3. A fixed set of values
  4. switch
  5. Coming from PHP
  6. Practice
  7. Remember

In PHP, a booking is often an associative array: ['guest' => 'Astrid', 'nights' => 3], where any key may be missing or misspelled. In Go it is a struct: a type you define, with named fields of fixed types, checked by the compiler.

Today: structs, slices of structs and the copy trap of range, a named type with constants for a fixed set of values like log levels, and switch.

Structs

1. Define a type, make a value

type Booking struct { … } defines a new type with three fields. A struct literal creates a value of it, naming each field.

main.go
package main

import "fmt"

type Booking struct {
	Guest  string
	Nights int
	Paid   bool
}

func main() {
	b := Booking{Guest: "Astrid", Nights: 3, Paid: true}

	fmt.Println(b.Guest, "stays", b.Nights, "nights")
	fmt.Printf("%v\n", b)
	fmt.Printf("%+v\n", b)
}
$ go run .
Astrid stays 3 nights
{Astrid 3 true}
{Guest:Astrid Nights:3 Paid:true}

Fields are read and written with a dot: b.Nights = 4. %v prints the values; %+v adds the field names, which is what you want in a log line or while debugging.

Like a class with public typed properties and no methods yet. Methods come in Week 2. The field names start with a capital letter, which will matter once code is split into packages; for a type you share, that is the usual style.

2. Fields you leave out are zero

A struct literal does not have to name every field. The ones you leave out get their zero value, and so does every field of a struct declared with var.

main.go
package main

import "fmt"

type Booking struct {
	Guest  string
	Nights int
	Paid   bool
}

func main() {
	draft := Booking{Guest: "Bjorn"}
	var empty Booking

	fmt.Printf("%+v\n", draft)
	fmt.Printf("%+v\n", empty)
}
$ go run .
{Guest:Bjorn Nights:0 Paid:false}
{Guest: Nights:0 Paid:false}

There is no constructor that must run. When a struct needs rules (nights must be at least 1), write a function that checks them and returns the struct and an error, the shape from the errors lesson: func newBooking(guest string, nights int) (Booking, error).

3. A field that does not exist

A misspelled key in a PHP array is a new key, silently. A misspelled field in Go does not compile:

main.godoes not compile
package main

import "fmt"

type Booking struct {
	Guest  string
	Nights int
}

func main() {
	b := Booking{Guest: "Astrid", Night: 3}

	fmt.Println(b)
}
go build
# hello
./main.go:11:32: unknown field Night in struct literal of type Booking

The compiler knows every field of every struct. That is the main reason to turn the arrays you pass around into structs.

A slice of structs

4. Loop over records

[]Booking is a slice of bookings: the Go version of a list of rows.

main.go
package main

import "fmt"

type Booking struct {
	Guest  string
	Nights int
}

func main() {
	bookings := []Booking{
		{Guest: "Astrid", Nights: 3},
		{Guest: "Bjorn", Nights: 7},
		{Guest: "Clara", Nights: 2},
	}

	total := 0
	for _, b := range bookings {
		total += b.Nights
	}

	fmt.Println(len(bookings), "bookings,", total, "nights")
}
$ go run .
3 bookings, 12 nights

Inside the braces of a []Booking, each element can leave out the type name: {Guest: "Astrid", Nights: 3} instead of Booking{…}.

5. range copies each struct

The copy from the slices lesson matters here. Changing b changes the copy, and the slice stays the same:

main.go
package main

import "fmt"

type Booking struct {
	Guest  string
	Nights int
}

func main() {
	bookings := []Booking{{Guest: "Astrid", Nights: 3}, {Guest: "Bjorn", Nights: 7}}

	for _, b := range bookings {
		b.Nights++
	}
	fmt.Println("after the copy loop: ", bookings)

	for i := range bookings {
		bookings[i].Nights++
	}
	fmt.Println("after the index loop:", bookings)
}
$ go run .
after the copy loop:  [{Astrid 3} {Bjorn 7}]
after the index loop: [{Astrid 4} {Bjorn 8}]

Nothing warns you about the first loop: it compiles, go vet and staticcheck are quiet, and the program prints the old numbers. To change elements, loop over the indexes with for i := range bookings and write through bookings[i].

This is the opposite of PHP, where foreach ($bookings as &$b) needs the & to change the original, and plain foreach over an array of objects changes the objects. In Go, a struct in a slice is a value, not a reference to an object.

A fixed set of values

6. A named type with constants

Go has no enum keyword. You make a new type from int, then a block of constants of that type. iota counts up from 0 inside the block.

main.go
package main

import "fmt"

type Level int

const (
	Debug Level = iota
	Info
	Warning
	Error
)

func main() {
	var current Level = Warning

	fmt.Println(Debug, Info, Warning, Error)
	fmt.Println("current:", current, "is serious:", current >= Warning)
}
$ go run .
0 1 2 3
current: 2 is serious: true

In a const ( … ) block, a line with only a name repeats the line above it, with iota one higher: Info is Level(1), Warning is Level(2). The order is the severity, so >= compares levels.

Level is a new type, not an int: passing a plain int where a Level is expected needs a conversion, so the signature func log(level Level, …) documents itself. It prints as a number for now; Week 2 gives it a name with a method.

switch

7. switch with no break

A switch runs the first matching case and stops. There is no break to forget, and one case can list several values.

main.go
package main

import (
	"errors"
	"fmt"
)

type Level int

const (
	Debug Level = iota
	Info
	Warning
	Error
)

func parseLevel(text string) (Level, error) {
	switch text {
	case "DEBUG":
		return Debug, nil
	case "INFO", "NOTICE":
		return Info, nil
	case "WARNING":
		return Warning, nil
	case "ERROR", "CRITICAL", "ALERT", "EMERGENCY":
		return Error, nil
	default:
		return Debug, errors.New("unknown level " + text)
	}
}

func main() {
	level, err := parseLevel("CRITICAL")
	fmt.Println(level, err)

	level, err = parseLevel("LOUD")
	fmt.Println(level, err)
}
$ go run .
3 <nil>
0 unknown level LOUD

Laravel’s logger writes eight levels, from DEBUG to EMERGENCY; this program folds them into four. default is the case for everything else. On an error the function still has to return a Level; it returns the zero one, Debug, and the caller must not use it.

PHP’s match is the closer relative: no fall-through, several values per arm. Go’s switch can also run statements in a case, not only return a value.

8. switch with no value

Leave out the value and each case is a condition. It is a cleaner chain of if … else if.

main.go
package main

import "fmt"

func discountPercent(nights int) int {
	switch {
	case nights >= 28:
		return 30
	case nights >= 7:
		return 10
	default:
		return 0
	}
}

func main() {
	fmt.Println(discountPercent(3), discountPercent(7), discountPercent(30))
}
$ go run .
0 10 30

The cases are checked top to bottom, so the order is part of the logic: put the most specific condition first, as here.

Coming from PHP

Booking.php
<?php
enum Level: int
{
    case Debug = 0;
    case Info = 1;
    case Warning = 2;
    case Error = 3;
}

final class Booking
{
    public function __construct(
        public string $guest,
        public int $nights,
        public bool $paid = false,
    ) {}
}

$level = match ($text) {
    'INFO', 'NOTICE' => Level::Info,
    default => throw new ValueError("unknown level $text"),
};

A struct is close to a PHP class with constructor-promoted public properties. The difference is the copy: assigning a struct, passing it to a function or taking it out of a slice copies all its fields, while a PHP object is always shared.

PHP 8.1’s enums are stricter than Go’s constants: Level::from(9) throws, while in Go Level(9) is a valid Level that matches none of the constants. A switch with a default case, as in parseLevel, is where Go code catches that.

PracticeA Tour of Go: structs and switch, one small program

In A Tour of Go, do Structs, Struct Fields and Struct Literals; the pointer pages next to them are Week 2. Then the flow control pages Switch to Switch with no condition. Defer and Stacking defers prepare the build day.

Exercise: a status report

Define type Status int with the constants Pending, Confirmed and Cancelled, and a Booking struct with Guest string, Nights int and Status Status. Make a slice of five bookings. Cancel every booking of more than 10 nights (change the slice, not a copy), then print the number of bookings per status, using a switch to turn each status into a label.

Show the solution
main.go
package main

import "fmt"

type Status int

const (
	Pending Status = iota
	Confirmed
	Cancelled
)

type Booking struct {
	Guest  string
	Nights int
	Status Status
}

func label(s Status) string {
	switch s {
	case Pending:
		return "pending"
	case Confirmed:
		return "confirmed"
	case Cancelled:
		return "cancelled"
	default:
		return "unknown"
	}
}

func main() {
	bookings := []Booking{
		{Guest: "Astrid", Nights: 3, Status: Confirmed},
		{Guest: "Bjorn", Nights: 14, Status: Confirmed},
		{Guest: "Clara", Nights: 2},
		{Guest: "Dagny", Nights: 21},
		{Guest: "Erik", Nights: 5, Status: Confirmed},
	}

	for i := range bookings {
		if bookings[i].Nights > 10 {
			bookings[i].Status = Cancelled
		}
	}

	counts := map[Status]int{}
	for _, b := range bookings {
		counts[b.Status]++
	}
	for _, s := range []Status{Pending, Confirmed, Cancelled} {
		fmt.Printf("%-9s %d\n", label(s), counts[s])
	}
}
$ go run .
pending   1
confirmed 2
cancelled 2

The map’s key is a Status, and the report loops over a fixed slice of statuses instead of the map, so the order never changes. Clara and Dagny have no Status in the literal, so they are Pending, the zero value.

Remember

  • Turn arrays you pass around into structs: the compiler then knows every field.
  • range gives copies; change slice elements through their index.
  • A fixed set of values is a named type with iota constants, and a switch with a default catches the rest.

Tomorrow is the build day: everything from this week in one tool that reads a real laravel.log.