SyntaxPilot
Courses/Go Programming/Lesson 19

Go Programming · Lesson 19 of 89 · 16 min

Structs and type declarations

struct typesfieldsstruct literals (keyed and positional)anonymous structsnested structsstruct comparison and equalitycomparable typescopying structsexported vs unexported fields (capitalisation)struct tags (preview)type definitions (defined types)type aliasesunderlying type

These are the notes for Go episode 19. In episode 18 Raju's chai stall printed a neat bill, but every order was three loose values: a name, a quantity and a rate, kept in three separate slices. Today that causes a real bug, and fixing it, you will invent Go's struct. You will learn struct types and fields, positional and keyed struct literals, the zero value of a struct, slices of structs, how structs are copied, pointers to structs, struct equality and comparable types, structs as map keys, anonymous and nested structs, exported vs unexported fields, struct tags with encoding/json, type definitions like type Rupees float64, underlying types and conversion, and type aliases like type Money = Rupees. Every example runs as-is in the SyntaxPilot compiler (language: Go); outputs and errors are from real runs (Go 1.24). The two-package example was run in a local module.

The problem: three registers that drift apart

Imagine Raju keeps three separate registers: one for item names, one for quantities, one for rates. Row 2 of each register together means one order. In code, that is three parallel slices: slices whose elements at the same index belong together.

A customer cancels the samosa. Raju erases it from the names register and forgets the other two.

package main

import "fmt"

func main() {
    items := []string{"masala chai", "samosa", "bun maska"}
    qty := []int{3, 2, 1}
    rate := []float64{12.5, 15, 35}

    // the customer cancels the samosa
    items = append(items[:1], items[2:]...)

    for i := range items {
        amt := float64(qty[i]) * rate[i]
        fmt.Printf("%-12s %d x %5.2f = %6.2f\n", items[i], qty[i], rate[i], amt)
    }
}
masala chai  3 x 12.50 =  37.50
bun maska    2 x 15.00 =  30.00
  • Line 11 removes index 1 (the samosa) with the append(s[:i], s[i+1:]...) trick from episode 14, but only from items.
  • Bun maska is billed 2 x 15: that is the samosa's quantity and rate. The real bun maska was 1 x 35.
  • No error, no crash, just a wrong bill. The compiler can't help, because nothing in the code says these three values belong together. Only the index ties them, and indexes drift.

We need one value that holds a whole order.

Your first struct: one order card

Real stalls solve this with an order card: one card, with labelled boxes, for one order. Tear up the card, and the whole order goes with it.

At the stall In Go Name
A printed card design type Order struct { ... } a struct type
The labelled boxes: Item, Qty, Rate Item string, Qty int fields
One filled card: chai, 3, 12.5 Order{"masala chai", 3, 12.5} a struct value, written with a struct literal
  • A struct is a type that groups several named values into one value. "Struct" is short for structure.
  • Each named part is a field. Every field has its own name and its own type.
  • A literal is a value written directly in the code (3, "chai"). A struct literal is the type name followed by the field values in curly braces.
package main

import "fmt"

type Order struct {
    Item string
    Qty  int
    Rate float64
}

func main() {
    o := Order{"masala chai", 3, 12.5}
    fmt.Println(o)
    fmt.Println(o.Item, float64(o.Qty)*o.Rate)

    o.Qty = 4
    fmt.Printf("%+v\n", o)

    var blank Order
    fmt.Printf("%+v\n", blank)
}
{masala chai 3 12.5}
masala chai 37.5
{Item:masala chai Qty:4 Rate:12.5}
{Item: Qty:0 Rate:0}
  • type Order struct { ... } is a type declaration: it creates a new type named Order, not a variable. After it, Order can be used anywhere a type can: var o Order, []Order, func f(o Order).
  • Field access uses a dot: o.Item reads a field, o.Qty = 4 writes one.
  • Println shows the field values in curly braces; %+v (episode 18) adds the field names.
  • The zero value of a struct: var blank Order has no literal, but it still works. Every field gets its own zero value: "" for the string, 0 for the int, 0 for the float64. A struct is never half-built garbage; it is always ready to use.
  • float64(o.Qty) converts the int before multiplying (episode 4: Go never mixes types silently).

A slice of structs: one delete removes the whole order

Now the fix: one slice, of Order values.

package main

import "fmt"

type Order struct {
    Item string
    Qty  int
    Rate float64
}

func main() {
    orders := []Order{
        {"masala chai", 3, 12.5},
        {"samosa", 2, 15},
        {"bun maska", 1, 35},
    }
    orders = append(orders[:1], orders[2:]...)

    for _, o := range orders {
        amt := float64(o.Qty) * o.Rate
        fmt.Printf("%-12s %d x %5.2f = %6.2f\n", o.Item, o.Qty, o.Rate, amt)
    }
}
masala chai  3 x 12.50 =  37.50
bun maska    1 x 35.00 =  35.00
  • Bun maska, 1 x 35: correct. One delete removed the name, the quantity and the rate together, because they are one value now.
  • Inside a slice (or array or map) literal, Go lets you skip the type name before each {: it already knows each element is an Order. {"samosa", 2, 15} means Order{"samosa", 2, 15}.
  • A literal that builds a struct, array, slice or map with {...} is called a composite literal ("composite" = made of parts). Order{...}, []Order{...} and map[Seat]string{...} are all composite literals.

Positional vs keyed literals

Business grows. Raju adds a fourth box to the card: Table, which table ordered. Every literal that listed three values by position now has three values for four boxes.

package main

import "fmt"

type Order struct {
    Item  string
    Qty   int
    Rate  float64
    Table int
}

func main() {
    a := Order{"samosa", 2, 15}
    fmt.Printf("%+v\n", a)
}
# command-line-arguments
./main.go:13:31: too few values in struct literal of type Order
  • A positional literal matches values to fields only by their position: first value to the first field, and so on. It must give every field, in order.
  • Add a field, and every positional literal in your program breaks. Reorder two fields of the same type, and positional literals silently put values in the wrong boxes.

A keyed literal writes the field name before each value: Item: "samosa".

package main

import "fmt"

type Order struct {
    Item  string
    Qty   int
    Rate  float64
    Table int
}

func main() {
    a := Order{Item: "samosa", Qty: 2, Rate: 15}
    b := Order{Table: 4, Item: "chai", Qty: 1, Rate: 12.5}
    c := Order{Item: "bun maska"}

    fmt.Printf("%+v\n%+v\n%+v\n", a, b, c)
}
{Item:samosa Qty:2 Rate:15 Table:0}
{Item:chai Qty:1 Rate:12.5 Table:4}
{Item:bun maska Qty:0 Rate:0 Table:0}
  • The order of keys doesn't matter: b gave Table first and it still landed in the right box.
  • You can leave fields out: missing fields get their zero value (a has Table:0, c has only an Item). Order{} is a literal with every field at zero.
  • Keyed literals keep working when the type grows. Prefer keyed literals, especially for types from other packages (whose authors may add fields). go vet even warns about positional literals of struct types from other packages ("composites" check).
  • You can't mix the two styles in one literal (see Common mistakes).

Copying structs: a photocopy vs the card's location

If you photocopy an order card and scribble on the copy, the original card doesn't change. Assigning a struct in Go works the same way: b := a copies every field. This is called value semantics: the variable holds the whole value, not a link to it. The same copy happens when you pass a struct to a function, return it, or store it in a slice or map.

But if you tell someone "the card on hook 3", they walk there and edit the real card. That is a pointer (episode 11): a value that holds the address (the memory location) of another value. &a gives the address of a.

package main

import "fmt"

type Order struct {
    Item string
    Qty  int
    Rate float64
}

func main() {
    a := Order{Item: "chai", Qty: 1, Rate: 12.5}
    b := a // a full copy
    b.Qty = 10
    fmt.Println(a.Qty, b.Qty)

    p := &a   // a pointer to a
    p.Qty = 5 // same as (*p).Qty = 5
    fmt.Println(a.Qty, p.Qty)
    fmt.Printf("%+v\n", p)
}
1 10
5 5
&{Item:chai Qty:5 Rate:12.5}
  • 1 10: changing the copy b left a alone.
  • 5 5: writing through the pointer p changed a itself.
  • A pointer to a struct has the type *Order (read "pointer to Order").
  • Automatic dereference: to dereference a pointer means to go to the value it points at, written *p. For a pointer to a struct, Go lets you write p.Qty instead of (*p).Qty; it dereferences for you. The two forms mean exactly the same thing. (The brackets matter: *p.Qty would mean *(p.Qty), which doesn't compile because Qty is not a pointer.)
  • %+v of a pointer to a struct prints an & before the fields: a hint that this is a pointer, not the struct itself.
  • &Order{Item: "samosa"} makes a struct and gives you a pointer to it in one step; its %T is *main.Order.

The range-copy gotcha

package main

import "fmt"

type Order struct {
    Item string
    Qty  int
    Rate float64
}

func main() {
    orders := []Order{{"chai", 1, 12.5}, {"samosa", 2, 15}}

    for _, o := range orders {
        o.Qty++ // changes the copy o only
    }
    fmt.Println(orders[0].Qty, orders[1].Qty)

    for i := range orders {
        orders[i].Qty++
    }
    fmt.Println(orders[0].Qty, orders[1].Qty)
}
1 2
2 3
  • 1 2: nothing changed. In for _, o := range orders, o is a copy of each element. We edited the photocopy.
  • The second loop uses the index and writes orders[i].Qty, the real element: now 2 3.
  • Another fix: p := &orders[i] then p.Qty++. Or store pointers in the slice, []*Order; then o is a copy of the pointer, which still points at the real order (quiz 5).

Addressable values (briefly)

&x and x.Field = ... need a value that has a fixed place in memory: an addressable value. Variables, slice elements (orders[i]), and fields of addressable structs are addressable. A map element is not (the map may move its elements when it grows), so this fails:

m := map[string]Order{"t4": {"chai", 1}}
m["t4"].Qty = 2
./main.go:12:5: cannot assign to struct field m["t4"].Qty in map

Fix: copy out, change, store back: o := m["t4"]; o.Qty = 2; m["t4"] = o (prints map[t4:{chai 2}]), or use map[string]*Order.

Copying is shallow

"Copies every field" means exactly that: a slice field is copied as a slice header (pointer, length, capacity; episode 13), so both copies share the same backing array.

package main

import "fmt"

type Bill struct {
    Table  int
    Orders []string
}

func main() {
    a := Bill{4, []string{"chai", "samosa"}}
    b := a
    b.Table = 9
    b.Orders[0] = "tea"
    fmt.Println(a.Table, a.Orders)
    fmt.Println(b.Table, b.Orders)

    c := a
    c.Orders = append([]string(nil), a.Orders...) // a deep copy of the slice
    c.Orders[0] = "lassi"
    fmt.Println(a.Orders, c.Orders)
}
4 [tea samosa]
9 [tea samosa]
[tea samosa] [lassi samosa]

Table was copied (a stays 4), but b.Orders[0] = "tea" changed a's orders too. This is a shallow copy. To get an independent copy (a deep copy), copy the slice's elements yourself (append([]string(nil), ...) or slices.Clone). The same goes for map and pointer fields.

Comparing structs: two tickets for the same seat

Two railway tickets that both say coach S4, seat 32 are for the same seat. Two structs are equal when every field is equal, and Go lets you check that with ==. And the seat chart maps each seat to a passenger: a struct can be a map key.

package main

import "fmt"

type Seat struct {
    Coach  string
    Number int
}

func main() {
    a := Seat{"S4", 32}
    b := Seat{Coach: "S4", Number: 32}
    fmt.Println(a == b, a == Seat{"B1", 32})

    booked := map[Seat]string{a: "Asha"}
    booked[Seat{"B1", 7}] = "Ravi"
    fmt.Println(booked[Seat{"S4", 32}], len(booked))
}
true false
Asha 2
  • Struct equality: a == b is true because coach and number are both equal (it doesn't matter that one is positional and one keyed). A different coach makes it false. != is the opposite.
  • Looking up a brand-new Seat value with the same fields finds Asha: map lookup compares keys with ==.
  • Map key requirement: a map's key type must be comparable. A struct of comparable fields is a perfect "composite key" (two values together forming one key), much nicer than gluing "S4-32" into a string.

Comparable types

package main

import "fmt"

type Order struct {
    Item     string
    Toppings []string
}

func main() {
    a := Order{"chai", []string{"ginger"}}
    b := Order{"chai", []string{"ginger"}}
    fmt.Println(a == b)
}
# command-line-arguments
./main.go:13:17: invalid operation: a == b (struct containing []string cannot be compared)

A comparable type is one whose values Go can compare with == and !=.

Comparable Not comparable
numbers, strings, bools slices
pointers (equal = same address) maps
channels, interfaces functions
arrays of comparable elements structs or arrays containing any of these
structs whose fields are all comparable
  • A struct with a slice, map or function field can't use == and can't be a map key:
./main.go:11:14: invalid map key type Order
  • Compare such fields yourself, for example with slices.Equal from episode 14 (practice 4). Comparing to nil is allowed for a slice field: a.Toppings == nil.

Arrays inside structs, pointer fields, and %#v

package main

import "fmt"

type Berth struct {
    Coach string
    Seats [3]int
}

type Card struct {
    Item string
    Note *string
}

func main() {
    a := Berth{"S4", [3]int{31, 32, 33}}
    b := Berth{"S4", [3]int{31, 32, 33}}
    fmt.Println(a == b)
    fmt.Printf("%#v\n", a)

    n1, n2 := "less sugar", "less sugar"
    x := Card{"chai", &n1}
    y := Card{"chai", &n2}
    z := Card{"chai", &n1}
    fmt.Println(x == y, x == z, *x.Note == *y.Note)
}
true
main.Berth{Coach:"S4", Seats:[3]int{31, 32, 33}}
false true true
  • An array (fixed length, episode 13) of comparable elements is comparable, so a struct containing one still supports ==; the arrays are compared element by element.
  • %#v prints the struct as Go syntax: package-qualified type name, field names, quoted strings.
  • A pointer field is compared by address, not by what it points at: x == y is false even though both notes say "less sugar", because they point at two different variables. x == z is true (same address). Compare *x.Note == *y.Note when you mean the text.

Anonymous structs: a one-off card

Sometimes you need a struct just once. An anonymous struct is a struct type with no name: you write struct { ...fields... } and then the values, right there.

package main

import "fmt"

func main() {
    stall := struct {
        Name string
        Open bool
    }{"Raju's Chai", true}
    fmt.Printf("%+v\n%T\n", stall, stall)

    tests := []struct {
        qty        int
        rate, want float64
    }{
        {3, 12.5, 37.5},
        {2, 15, 30},
    }
    for _, t := range tests {
        got := float64(t.qty) * t.rate
        fmt.Println(got, got == t.want)
    }
}
{Name:Raju's Chai Open:true}
struct { Name string; Open bool }
37.5 true
30 true
  • %T shows the type as struct { Name string; Open bool }: there is no name like main.Order, because we never declared one.
  • The most common use is a table of test cases (a "table-driven test"): a slice of anonymous structs, each with an input and the wanted result, checked in a loop. You will use this a lot in episode 40, on testing (practice 5).
  • Fields of the same type can share a line: rate, want float64.
  • Two anonymous struct types with the same fields, in the same order, with the same types (and tags) are the same type.

Nested structs: a customer with an address

A field can itself be a struct. That is a nested struct.

package main

import "fmt"

type Address struct {
    Street, City, Pin string
}

type Customer struct {
    Name string
    Home Address
}

func main() {
    c := Customer{
        Name: "Asha",
        Home: Address{Street: "MG Road", City: "Pune", Pin: "411001"},
    }
    fmt.Println(c.Home.City)

    c.Home.Pin = "411038"
    fmt.Printf("%+v\n", c)
}
Pune
{Name:Asha Home:{Street:MG Road City:Pune Pin:411038}}
  • Street, City, Pin string declares three string fields on one line.
  • c.Home.City reaches inside, one dot per level.
  • c.Home.Pin = "411038" changes just that inner field (c is a variable, so c.Home is addressable).
  • %+v shows the inner struct in its own braces.
  • The inner struct is stored inside the outer one (not as a link), so copying a Customer copies the address too.
  • (There is also a form with no field name, struct { Address }, called embedding; it comes with methods in episode 20 and later.)

Exported fields and tags: the front counter and the back kitchen

A restaurant has a front counter that customers see, and a back kitchen only staff enter. Go decides which is which with the first letter of a name:

At a restaurant In Go Name
Front counter, customers can see it Item (capital first letter) exported: visible to other packages
Back kitchen, staff only item (lowercase first letter) unexported: only inside its own package
A label for delivery apps: "item" not "Item" `json:"item"` a struct tag: extra information for tools
  • A package (episode 1) is a folder of Go files that share one package name; fmt and encoding/json are packages. Episode 27 covers packages fully.
  • The rule applies to everything at package level: types (Order vs order), functions (fmt.Println), constants, and struct fields. Inside its own package, everything is visible.

encoding/json can only see exported fields

JSON (JavaScript Object Notation) is a text format programs use to send data to each other, like the menu a delivery app downloads: {"item":"chai","qty":3}. json.Marshal, from the package encoding/json, turns a Go value into JSON text (as a []byte; "marshal" = arrange for sending). It lives in another package, so it can only see exported fields.

package main

import (
    "encoding/json"
    "fmt"
)

type secret struct{ item string }

type Order struct{ Item string }

type Tagged struct {
    Item string `json:"item"`
}

func main() {
    a, _ := json.Marshal(secret{"chai"})
    b, _ := json.Marshal(Order{"chai"})
    c, _ := json.Marshal(Tagged{"chai"})
    fmt.Println(string(a))
    fmt.Println(string(b))
    fmt.Println(string(c))
}
{}
{"Item":"chai"}
{"item":"chai"}
  • secret gives empty braces: encoding/json couldn't see item, so it silently left it out. No error.
  • Order gives the capitalised key "Item", the Go field name.
  • Tagged gives lowercase "item", the name the tag asked for.
  • A struct tag is a string written after a field's type. By convention it is a list of key:"value" pairs, here json:"item". Tags do nothing by themselves: a package such as encoding/json has to read them (using reflection, a way for a program to inspect types while running). Episode 35 covers JSON tags fully (omitempty, -, decoding).
  • The tag is written in backquotes: a raw string literal. Inside `...` nothing is an escape, so the double quotes need no backslashes. The same tag as a normal string would be "json:\"item\"".
  • string(a) converts the []byte to a string for printing. _ throws away the error only to keep the demo short.

Two packages: the compiler enforces the back-kitchen rule

A local module named chai (a module is a project with a go.mod file; go mod init chai), with two packages: bill and main.

bill/bill.go:

package bill

type Order struct {
    Item string
    qty  int
}

main.go (gofmt-formatted, indented with a tab):

package main

import (
    "chai/bill"
    "fmt"
)

func main() {
    o := bill.Order{Item: "chai"}
    fmt.Println(o.Item, o.qty)
}
$ go run .
# chai
./main.go:10:24: o.qty undefined (cannot refer to unexported field qty)
  • main may use o.Item, but not o.qty. The compiler enforces it.
  • Setting it in a literal fails too: bill.Order{Item: "chai", qty: 2} gives cannot refer to unexported field qty in struct literal of type bill.Order.
  • This is how a package keeps its own data safe: only its own functions (and later its methods) can touch unexported fields.

Defined types: Rupees and Kg

A real story. On 23 September 1999 NASA lost the Mars Climate Orbiter. Thruster data from one piece of software was in English units (pounds), and other software read it as metric (newtons). The spacecraft flew about 170 km closer to Mars than planned, and was lost. (Source: Physics Today, "Mars Climate Orbiter lost".)

In the code, both were just numbers. A float64 in pounds and a float64 in newtons look identical, so nothing stops you adding them. Raju has the same risk with rupees and kilograms. What if each unit had its own type?

package main

import "fmt"

type Rupees float64
type Kg float64

func main() {
    var price Rupees = 120 // per kg
    var sugar Kg = 2
    fmt.Println(price * sugar)
}
# command-line-arguments
./main.go:11:17: invalid operation: price * sugar (mismatched types Rupees and Kg)
  • type Rupees float64 is a type definition: it creates a brand-new type called Rupees, stored like a float64. Rupees is a defined type (a type with its own name, created by a type definition). type Order struct {...} is also a type definition, so Order is a defined type too.
  • Even though both are float64 inside, Rupees and Kg are different types, and Go never mixes different types silently. The unit bug is caught before the program runs.
  • Type declaration is the umbrella word: a line starting with type. There are two kinds: type definitions (type A B) and type aliases (type A = B, below).

The underlying type

Every type has an underlying type: what it is really made of.

Type Underlying type
Rupees (from type Rupees float64) float64
Kg float64
Order (from type Order struct {...}) that struct { Item string; ... }
float64, int, string (predeclared) itself
  • The underlying type decides how the value is stored and which operators work. Rupees can be added, multiplied and compared because float64 can.
  • Conversion: when two types have the same underlying type, you can convert between them by writing the type name like a function: Rupees(sugar), float64(price). A conversion copies the value with a new type; the bits are the same.
  • An untyped constant (episode 5) such as 3, 12.5 or const gst = 0.05 has no fixed type yet, so it fits any numeric defined type: price * 3 needs no conversion.
  • Plain assignment between two different named types is an error, even with the same underlying type.
package main

import "fmt"

type Rupees float64
type Kg float64

func main() {
    var price Rupees = 120 // per kg
    var sugar Kg = 2
    total := price * Rupees(sugar)
    fmt.Printf("%v %T\n", total, total)

    tea := Rupees(12.5) * 3
    fmt.Printf("%.2f %T\n", tea, tea)

    var cash float64 = 500
    price = Rupees(cash)
    fmt.Println(price, float64(price)+1)
}
240 main.Rupees
37.50 main.Rupees
500 501
  • Rupees(sugar) converts on purpose, so the multiplication is allowed. The result's type is main.Rupees.
  • Rupees(12.5) * 3: the untyped 3 becomes a Rupees.
  • A conversion shows the reader you meant it. Now try without converting:
package main

import "fmt"

type Rupees float64
type Kg float64

func main() {
    var cash float64 = 500
    var price Rupees = cash
    fmt.Println(price)
}
# command-line-arguments
./main.go:10:24: cannot use cash (variable of type float64) as Rupees value in variable declaration

Untyped constants fit, typed variables don't: with const gst = 0.05 and var bill Rupees = 200, fmt.Println(bill*gst, bill+10) prints 10 210, and %T of bill*gst is main.Rupees. But with var rate float64 = 0.05, bill * rate fails: invalid operation: bill * rate (mismatched types Rupees and float64).

A defined type does not inherit methods

A type definition copies the underlying type, not its methods (functions attached to a type, episode 20). time.Duration has a Minutes() method; with type Wait time.Duration, d := 90 * time.Second and w := Wait(d), d.Minutes() is 1.5 but w.Minutes() fails (real run):

./main.go:14:19: w.Minutes undefined (type Wait has no field or method Minutes)

Fields of a struct type do carry over, because they are part of the underlying type. This is also why defined types are useful: you can give Rupees its own methods, such as a String() that prints "Rs 240.00", next episode.

Type aliases: Raju and Rajesh

There is a second kind of type declaration.

Type definition Type alias
type Rupees float64 type Money = Rupees
a brand-new type a second name for the same type
Rupees is not float64; convert with Rupees(x) Money is Rupees; no conversion needed
%T prints main.Rupees %T prints the original: main.Rupees

A type alias (with =) is a nickname, like "Raju" for Rajesh: two names, one person.

package main

import "fmt"

type Rupees float64
type Money = Rupees // an alias: a second name

func main() {
    var price Rupees = 120
    var m Money = price // no conversion needed
    fmt.Printf("%v %T\n", m+price, m)

    var b byte = 'A'
    var r rune = 'अ'
    var u uint8 = b
    fmt.Printf("%T %T %v\n", b, r, u)
}
240 main.Rupees
uint8 int32 65
  • m and price can be assigned and added freely, and %T of m says main.Rupees, not Money: an alias is not a separate type at all.
  • byte is an alias for uint8 and rune is an alias for int32, built into Go (episode 17). That is why var u uint8 = b needs no conversion, and why %T prints uint8 and int32. 'A' is 65.
  • Aliases exist mainly for moving code between packages: when a type moves, the old package keeps type Old = newpkg.Old so existing code still compiles. Day to day, you'll mostly define types, not alias them.

Alias vs definition side by side: with type Paise = int64 and type Price float64, fmt.Printf("%T %T\n", c, p) prints int64 main.Price (real run). The alias name vanishes completely in %T; the defined type keeps its own name. Also, %#v of a float-based defined type prints just the number (10, not main.Rupees(10)), so use %T when you need the type.

Expert corner: memory layout, struct{} and escape analysis

Field order, padding and alignment

A struct's fields are laid out in memory in the order you declare them. Each type has an alignment: a float64 must start at an address that is a multiple of 8 (on 64-bit machines). To satisfy this the compiler inserts unused bytes, called padding. unsafe.Sizeof reports how many bytes a value takes; unsafe.Alignof and unsafe.Offsetof show the alignment and where a field starts. (Package unsafe is for low-level inspection; reading sizes is safe.)

package main

import (
    "fmt"
    "unsafe"
)

type Loose struct {
    Paid  bool
    Total float64
    Open  bool
}

type Tight struct {
    Total float64
    Paid  bool
    Open  bool
}

func main() {
    fmt.Println(unsafe.Sizeof(Loose{}), unsafe.Sizeof(Tight{}))
    fmt.Println(unsafe.Alignof(Loose{}.Total), unsafe.Offsetof(Loose{}.Total), unsafe.Offsetof(Loose{}.Open))
    fmt.Println(unsafe.Sizeof(struct{}{}))
}

Real run on linux/amd64:

24 16
8 8 16
0
  • Loose: Paid (1 byte) + 7 bytes padding + Total (8, at offset 8) + Open (1, at offset 16) + 7 bytes padding at the end (so the next struct in an array is aligned) = 24 bytes.
  • Tight: same fields, biggest first: 8 + 1 + 1 + 6 padding = 16 bytes.
  • Ordering fields from largest to smallest can save memory when you have millions of values. For ordinary code, order fields for readability; worry about this only when profiling says so.

The empty struct

struct{} has no fields, and its size is 0 (last line above). Its only value is struct{}{}. It's used when you need "something" but no data: a set is a map[string]struct{} where only the keys matter (seen[item] = struct{}{}; adding "chai", "samosa", "chai" gives len(seen) = 2 in a real run), and a "signal only" channel is a chan struct{} (episode 29 onwards).

Returning a pointer to a local struct is safe

In C, returning the address of a local variable is a classic bug. In Go it's fine: the compiler's escape analysis notices the address "escapes" the function and puts the struct on the heap (memory that lives as long as something points to it, cleaned by the garbage collector) instead of the stack (memory freed when the function returns).

package main

import "fmt"

type Order struct {
    Item string
    Qty  int
}

func newOrder(item string) *Order {
    o := Order{Item: item, Qty: 1}
    return &o
}

func main() {
    p := newOrder("chai")
    fmt.Println(p.Item, p.Qty)
}
chai 1

go build -gcflags=-m main.go prints the compiler's decisions (real output):

# command-line-arguments
./main.go:10:6: can inline newOrder
./main.go:16:18: inlining call to newOrder
./main.go:17:16: inlining call to fmt.Println
./main.go:10:15: leaking param: item
./main.go:11:5: moved to heap: o
./main.go:17:16: ... argument does not escape
./main.go:17:18: p.Item escapes to heap
./main.go:17:26: p.Qty escapes to heap
  • moved to heap: o: the struct outlives newOrder, so it lives on the heap.
  • leaking param: item: the string passed in is stored somewhere that outlives the call (inside o).
  • The escapes to heap lines for p.Item and p.Qty come from fmt.Println, which takes its arguments as interfaces.
  • Functions named newX that return *X are Go's usual constructor pattern (episode 20).

Mini project: a Bill type

A Bill has a Table and Orders, a slice of Order structs: a struct holding a slice of structs.

package main

import "fmt"

type Order struct {
    Item string
    Qty  int
    Rate float64
}

type Bill struct {
    Table  int
    Orders []Order
}

func total(b Bill) (sum float64) {
    for _, o := range b.Orders {
        sum += float64(o.Qty) * o.Rate
    }
    return
}

func main() {
    b := Bill{4, []Order{{"masala chai", 3, 12.5}, {"samosa", 2, 15}}}
    fmt.Printf("Table %d: Rs %.2f\n", b.Table, total(b))
}
Table 4: Rs 67.50
  • total loops over the orders and adds up quantity times rate, using the named result sum from episode 9 (it starts at 0 and the bare return returns it).
  • One positional literal builds the whole bill, with the orders written inside (and their type names skipped).
  • Passing b to total copies the Bill (only the slice header, not the orders; cheap).

Extended version: Rupees, keyed literals, cancel, GST and JSON

Today's ideas in one program: a defined type Rupees, keyed literals, a pointer parameter that changes the bill, an untyped constant for GST, a neat receipt (episode 18) and JSON with tags.

package main

import (
    "encoding/json"
    "fmt"
)

type Rupees float64

type Order struct {
    Item string `json:"item"`
    Qty  int    `json:"qty"`
    Rate Rupees `json:"rate"`
}

type Bill struct {
    Table    int     `json:"table"`
    Customer string  `json:"customer"`
    Orders   []Order `json:"orders"`
}

const gstRate = 0.05

func total(b Bill) (sum Rupees) {
    for _, o := range b.Orders {
        sum += Rupees(o.Qty) * o.Rate
    }
    return
}

func cancel(b *Bill, item string) {
    for i, o := range b.Orders {
        if o.Item == item {
            b.Orders = append(b.Orders[:i], b.Orders[i+1:]...)
            return
        }
    }
}

func main() {
    b := Bill{
        Table:    4,
        Customer: "Asha",
        Orders: []Order{
            {Item: "masala chai", Qty: 3, Rate: 12.5},
            {Item: "samosa", Qty: 2, Rate: 15},
            {Item: "bun maska", Qty: 1, Rate: 35},
        },
    }
    cancel(&b, "samosa")

    for _, o := range b.Orders {
        fmt.Printf("%-12s %2d x %6.2f = %7.2f\n", o.Item, o.Qty, o.Rate, Rupees(o.Qty)*o.Rate)
    }
    sub := total(b)
    fmt.Printf("%-26s %7.2f\n", "Subtotal", sub)
    fmt.Printf("%-26s %7.2f\n", "GST 5%", sub*gstRate)
    fmt.Printf("%-26s %7.2f\n", "Total", sub*(1+gstRate))

    out, _ := json.Marshal(b)
    fmt.Println(string(out))
}
masala chai   3 x  12.50 =   37.50
bun maska     1 x  35.00 =   35.00
Subtotal                     72.50
GST 5%                        3.62
Total                        76.12
{"table":4,"customer":"Asha","orders":[{"item":"masala chai","qty":3,"rate":12.5},{"item":"bun maska","qty":1,"rate":35}]}
  • cancel takes *Bill so it can change the caller's Orders; with a plain Bill it would change a copy and the samosa would stay.
  • sub * gstRate works because gstRate is an untyped constant; the result is Rupees.
  • GST of 72.50 is exactly 3.625, and %.2f printed 3.62: when a value is exactly halfway, Go's formatting rounds to the even digit. Real billing code stores paise as an integer to avoid float rounding entirely.
  • The tags turn every key lowercase; Rupees marshals as a plain number, and the nested []Order becomes a JSON array.
  • Try it: replace Customer string with today's nested Customer struct with an Address.

The next problem: total is a separate function that takes a Bill. The bill can't calculate itself. Wouldn't b.Total() be nicer, just like b.Table? Episode 20 attaches functions to types: methods.

Common mistakes (and the real messages)

You wrote Real error / what happens Fix
Order{"samosa", 2, 15} (Order has 4 fields) too few values in struct literal of type Order keyed: Order{Item: "samosa", Qty: 2, Rate: 15}
Order{"chai", 2, 12.5} (Order has 2 fields) too many values in struct literal of type Order one value per field
Order{Item: "chai", 2} mixture of field:value and value elements in struct literal all keyed or all positional
Order{Item: "chai", Quantity: 2} unknown field Quantity in struct literal of type Order use the real field name, Qty
Order{Item: "chai", Item: "tea"} duplicate field name Item in struct literal give each field once
Item string declared twice in one struct Item redeclared + other declaration of Item field names must be unique
for _, o := range orders { o.Qty++ } (no error) values unchanged orders[i].Qty++
m["t4"].Qty = 2 (map of structs) cannot assign to struct field m["t4"].Qty in map copy out, change, store back; or map[string]*Order
a == b, struct with a []string field invalid operation: a == b (struct containing []string cannot be compared) compare fields; slices.Equal
a == b, struct with a map[string]float64 field invalid operation: a == b (struct containing map[string]float64 cannot be compared) compare fields; maps.Equal
map[Order]int where Order has a slice invalid map key type Order use a comparable key, e.g. an ID
field item used from another package o.qty undefined (cannot refer to unexported field qty) capitalise it, or add an exported function
json.Marshal of a struct with lowercase fields (no error) output {} capitalise fields; tags for lowercase JSON names
price * sugar (Rupees, Kg) invalid operation: price * sugar (mismatched types Rupees and Kg) convert on purpose: Rupees(sugar)
var price Rupees = cash (cash is float64) cannot use cash (variable of type float64) as Rupees value in variable declaration Rupees(cash)
calling a method of the original type on a defined type w.Minutes undefined (type Wait has no field or method Minutes) convert back: time.Duration(w).Minutes()
p.Item where p is a nil *Order panic: runtime error: invalid memory address or nil pointer dereference check p != nil

All messages above are from real go run main.go runs (Go 1.24); the compiler prefixes each with the position, for example ./main.go:11:30: mixture of field:value and value elements in struct literal. The duplicate field declaration prints two lines: ./main.go:8:5: Item redeclared and ./main.go:6:5: other declaration of Item.

Practice

  1. Write a Train struct with Name, Number and a slice of Coaches. Make one with a keyed literal and print it with %v, %+v and %#v.
  2. Use struct{ Row, Col int } as a map key for a tic-tac-toe board. What happens when you store at the same cell twice? What does looking up an empty cell return?
  3. Write type Celsius float64, type Fahrenheit float64 and a function toF(c Celsius) Fahrenheit. Print 85 °C (chai temperature) in Fahrenheit.
  4. Order has a Toppings []string field, so == doesn't compile. Write same(a, b Order) bool.
  5. Write a table-driven check (a slice of anonymous structs) for amount(qty int, rate float64) float64, including one deliberately wrong case.
  6. Write bump(o Order) and bumpPtr(o *Order) that add 1 to Qty. Which one changes the caller's order?
Solution

1.

package main

import "fmt"

type Train struct {
    Name    string
    Number  int
    Coaches []string
}

func main() {
    t := Train{Name: "Deccan Queen", Number: 12123, Coaches: []string{"C1", "C2", "D1"}}
    fmt.Printf("%v\n%+v\n%#v\n", t, t, t)
    fmt.Println(len(t.Coaches), t.Coaches[2])
}
{Deccan Queen 12123 [C1 C2 D1]}
{Name:Deccan Queen Number:12123 Coaches:[C1 C2 D1]}
main.Train{Name:"Deccan Queen", Number:12123, Coaches:[]string{"C1", "C2", "D1"}}
3 D1
  1. The second store at {0, 0} overwrites (keys are equal), so there are 2 entries. A missing key gives the zero value "" and ok == false.
package main

import "fmt"

type Cell struct {
    Row, Col int
}

func main() {
    board := map[Cell]string{}
    board[Cell{0, 0}] = "X"
    board[Cell{1, 1}] = "O"
    board[Cell{Row: 0, Col: 0}] = "O" // same key: overwrites

    fmt.Println(len(board), board[Cell{0, 0}], board[Cell{1, 1}])
    v, ok := board[Cell{2, 2}]
    fmt.Printf("%q %v\n", v, ok)
}
2 O O
"" false
  1. c*9/5 + 32 stays Celsius (the constants are untyped), then one conversion makes it Fahrenheit. toF(-40) works because -40 is an untyped constant.
package main

import "fmt"

type Celsius float64
type Fahrenheit float64

func toF(c Celsius) Fahrenheit {
    return Fahrenheit(c*9/5 + 32)
}

func main() {
    chai := Celsius(85)
    f := toF(chai)
    fmt.Printf("%.1f %T -> %.1f %T\n", chai, chai, f, f)
    fmt.Println(toF(-40) == -40)
}
85.0 main.Celsius -> 185.0 main.Fahrenheit
true
  1. slices.Equal compares length and every element in order, so a different topping order is "not the same".
package main

import (
    "fmt"
    "slices"
)

type Order struct {
    Item     string
    Toppings []string
}

func same(a, b Order) bool {
    return a.Item == b.Item && slices.Equal(a.Toppings, b.Toppings)
}

func main() {
    a := Order{"chai", []string{"ginger", "elaichi"}}
    b := Order{"chai", []string{"ginger", "elaichi"}}
    c := Order{"chai", []string{"elaichi", "ginger"}}
    fmt.Println(same(a, b), same(a, c))
}
true false

5.

package main

import "fmt"

func amount(qty int, rate float64) float64 {
    return float64(qty) * rate
}

func main() {
    tests := []struct {
        name string
        qty  int
        rate float64
        want float64
    }{
        {"three chai", 3, 12.5, 37.5},
        {"no order", 0, 15, 0},
        {"wrong want", 2, 15, 31},
    }
    for _, tc := range tests {
        got := amount(tc.qty, tc.rate)
        if got != tc.want {
            fmt.Printf("FAIL %s: got %v, want %v\n", tc.name, got, tc.want)
            continue
        }
        fmt.Println("ok  ", tc.name)
    }
}
ok   three chai
ok   no order
FAIL wrong want: got 30, want 31
  1. bump gets a copy; bumpPtr gets the address.
package main

import "fmt"

type Order struct {
    Item string
    Qty  int
}

func bump(o Order)     { o.Qty++ }
func bumpPtr(o *Order) { o.Qty++ }

func main() {
    o := Order{"chai", 1}
    bump(o)
    fmt.Println(o.Qty)
    bumpPtr(&o)
    fmt.Println(o.Qty)
}
1
2

Quick quiz

1. What does this print? (From the video.)

type P struct{ X, Y int }

func main() {
    a := P{1, 2}
    b := a
    b.X = 9
    fmt.Println(a, b, a == P{Y: 2, X: 1})
}
  • A. {9 2} {9 2} false
  • B. {1 2} {9 2} true
  • C. {1 2} {9 2} false
  • D. compile error
Answer

B. b := a copies the struct, so a stays {1 2}. A keyed literal can list fields in any order, so P{Y: 2, X: 1} equals a. Real output: {1 2} {9 2} true.

2. a := Bill{4, []string{"chai", "samosa"}}; b := a; b.Orders[0] = "tea". What is a.Orders?

Answer

[tea samosa]. Copying a struct copies the slice header, and both headers point at the same backing array (a shallow copy). Real output shown in "Copying is shallow".

3. With type Money = float64 and type Price float64, what does fmt.Printf("%T %T\n", m, p) print for var m Money = 5 and var p Price = 5?

Answer

float64 main.Price. Money is an alias (the same type as float64); Price is a new defined type.

4. With type Kg float64, which line does not compile? (a) var a Kg = 2 (b) const two = 2.0; var b Kg = two (c) var x float64 = 2; var c Kg = x (d) var c Kg = Kg(x)

Answer

(c): x is a typed float64 variable, so it needs the conversion Kg(x) as in (d). (a) and (b) use untyped constants, which fit. With (c) replaced by (d), the program prints 6 for a + b + c.

5. What does this print?

orders := []*Order{{"chai", 1}, {"samosa", 2}}
for _, o := range orders {
    o.Qty++
}
fmt.Println(orders[0].Qty, orders[1].Qty)
Answer

2 3. o is still a copy, but a copy of a pointer; it points at the same Order, so o.Qty++ (automatic dereference) changes the real one. Compare the []Order version, which printed 1 2.

Interview questions

1. What is a struct, and when would you use one instead of several variables or parallel slices?
A struct is a type that groups named fields, each with its own type, into one value. Use it whenever values belong together (an order's item, quantity and rate): they then move, copy, delete and pass to functions as one unit, and the compiler checks the field names and types. Parallel slices tie values only by index, which drifts silently.

2. Positional or keyed struct literals: which should you use and why?
Keyed, almost always. Keyed literals don't depend on field order, let you omit fields (they get zero values), and keep compiling when fields are added. Positional literals must list every field in order and break (or silently misassign) when the type changes. Positional is acceptable for tiny, stable local types like Point{1, 2}. go vet flags positional literals of other packages' structs.

3. Is a struct passed by value or by reference in Go? How do you let a function modify it?
By value: assignment, function calls, returns and range all copy every field. To modify the caller's struct, pass a pointer (*Order); field access through the pointer is automatically dereferenced. The copy is shallow: slice, map and pointer fields still share what they point to. Large structs are also often passed by pointer to avoid copying.

4. When can two structs be compared with ==? Can a struct be a map key?
When the struct type is comparable, meaning every field is comparable (numbers, strings, bools, pointers, channels, interfaces, arrays and structs of comparable types). Equality compares field by field; pointer fields compare by address. A struct with a slice, map or function field is not comparable (struct containing []string cannot be compared) and can't be a map key (invalid map key type). Comparable structs make good composite map keys.

5. How does Go decide whether a field is visible outside its package? Why did json.Marshal return {}?
By the first letter: uppercase is exported, lowercase is unexported (package-private). encoding/json is another package, so it can only see exported fields; a struct with only lowercase fields marshals to {} with no error. To get lowercase JSON keys, keep the field exported and add a tag: Item string `json:"item"`.

6. What is a struct tag, and who reads it?
A string literal (usually a raw string in backquotes) after a field's type, by convention key:"value" pairs like json:"item". The compiler stores it but gives it no meaning; packages such as encoding/json, database libraries or validators read it at run time through reflection.

7. What is the difference between type Rupees float64 and type Money = Rupees?
The first is a type definition: a new, distinct defined type whose underlying type is float64. Mixing it with float64 or other float-based types needs an explicit conversion, %T prints main.Rupees, and it does not inherit the methods of its source type. The second is an alias: just another name for Rupees, fully interchangeable, and %T prints main.Rupees. byte/uint8 and rune/int32 are built-in aliases. Aliases are mainly for refactoring across packages.

8. What is an underlying type, and when is a conversion allowed?
The type a type is really built from: float64 for Rupees, the struct type for Order, itself for predeclared types. It decides storage and operators. A conversion T(x) is allowed between types with identical underlying types (Rupees(sugar) for Kg), and also between numeric types (float64(n)). Untyped constants need no conversion if their value fits. Defined types catch unit mix-ups like the Mars Climate Orbiter's pounds vs newtons at compile time.

Glossary

Term Meaning Example
Parallel slices several slices whose elements at the same index belong together; fragile items, qty, rate
Struct a type that groups named fields into one value struct { Item string; Qty int }
Struct type a named or unnamed type built with struct { ... } type Order struct { ... }
Field one named, typed part of a struct Qty int
Field access reading or writing a field with a dot o.Item, o.Qty = 4
Literal a value written directly in the code 3, "chai"
Struct literal a struct value written as type name plus values in braces Order{"chai", 3, 12.5}
Composite literal a literal for a struct, array, slice or map []Order{{"chai", 1, 12.5}}
Positional literal values matched to fields by position; must give every field Order{"samosa", 2, 15}
Keyed literal values given with field names; any order, may omit fields Order{Item: "samosa"}
Zero value of a struct every field at its own zero value {Item: Qty:0 Rate:0}
Type declaration a type line: a definition or an alias type Kg float64
Value semantics assigning or passing copies the whole value b := a copies every field
Shallow copy a copy whose slice/map/pointer fields still share data b.Orders[0] changes a.Orders[0]
Deep copy a copy that also duplicates shared data append([]string(nil), a.Orders...)
Pointer a value holding the address of another value p := &a
Pointer to struct type *T, the address of a struct *Order
Dereference going to the value a pointer points at *p
Automatic dereference p.Field on a struct pointer means (*p).Field p.Qty = 5
Addressable has a fixed place in memory, so &x and field assignment work orders[i] yes, m["t4"] no
nil pointer a pointer to nothing; using its fields panics var p *Order
Comparable type a type whose values work with == and != Seat, string, [3]int
Struct equality two structs are equal when all fields are equal a == b
Map key requirement map keys must be of a comparable type map[Seat]string
Composite key a struct of several values used as one map key Seat{"S4", 32}
Anonymous struct a struct type with no name, used once struct{ Name string }{"Raju"}
Table-driven test a slice of anonymous structs of inputs and wanted results tests := []struct{...}{...}
Nested struct a struct field whose type is another struct c.Home.City
Embedding a struct field with a type but no name (later episodes) struct { Address }
Package a folder of Go files sharing one package name fmt, chai/bill
Module a project with a go.mod file go mod init chai
Exported starts with a capital letter; usable from other packages Item, Println
Unexported starts with a lowercase letter; only inside its package qty, secret
JSON a text format for sending data between programs {"item":"chai"}
encoding/json Go's package for JSON import "encoding/json"
json.Marshal turns a Go value into JSON bytes; sees only exported fields json.Marshal(Order{"chai"})
Struct tag a string after a field giving extra info to tools `json:"item"`
Reflection a program inspecting types and tags while running how json reads tags
Raw string literal a string in backquotes; no escapes inside `json:"item"`
Type definition type A B: creates a brand-new type type Rupees float64
Defined type a type with its own name made by a type definition Rupees, Order
Underlying type what a type is really made of; decides storage and operators float64 for Rupees
Conversion T(x): the same value with a different type Rupees(sugar)
Untyped constant a constant with no fixed type yet; fits any compatible type 3, const gst = 0.05
Type alias type A = B: a second name for the same type type Money = Rupees
byte built-in alias for uint8 var b byte = 'A'
rune built-in alias for int32 var r rune = 'अ'
Method a function attached to a type (episode 20); not inherited by defined types d.Minutes()
%+v / %#v / %T value with field names / as Go syntax / its type main.Berth{Coach:"S4", ...}
Alignment the address multiple a type must start at float64: 8
Padding unused bytes the compiler inserts for alignment Loose is 24 bytes, Tight 16
unsafe.Sizeof bytes a value occupies unsafe.Sizeof(Tight{}) = 16
Empty struct struct{}: no fields, size 0 map[string]struct{} as a set
Escape analysis the compiler deciding stack vs heap moved to heap: o
Stack / heap memory freed on return / memory kept while referenced newOrder returns &o
Constructor a newX function returning a ready *X newOrder("chai")

Summary

  • Parallel slices tie values only by index and drift silently; a struct keeps data that belongs together in one value.
  • type Order struct { Item string; Qty int; Rate float64 } declares a struct type with fields; o.Item reads and writes them.
  • Positional literals need every field in order; keyed literals (Order{Item: "chai"}) survive change and give missing fields their zero value. Prefer keyed.
  • Structs have value semantics: assignment, calls and range copy them (shallowly). A pointer (&a, *Order) edits the original, with automatic dereference (p.Qty).
  • == compares every field and works when all fields are comparable; comparable structs can be map keys. Slices, maps and functions are not comparable.
  • Anonymous structs have no name (great for test tables); nested structs hold other structs (c.Home.City).
  • Capitalised names are exported; encoding/json sees only exported fields; struct tags like `json:"item"` give tools extra information.
  • type Rupees float64 is a type definition: a new defined type with underlying type float64; mixing types needs a conversion, untyped constants fit. Like the Mars Climate Orbiter's pounds vs newtons, unit mix-ups become compile errors.
  • type Money = Rupees is a type alias: a second name; byte = uint8, rune = int32.

Next episode: Methods: attach functions to your types (receivers, value vs pointer receivers, method sets and constructors), so a Bill can calculate its own total with b.Total().