SyntaxPilot
Courses/Go Programming/Lesson 39
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Go Programming · Lesson 39 of 89

Reflection basics

reflect packagereflect.TypeOfreflect.ValueOfKind vs Typereading struct fields and tagssettability and CanSetElemcalling methods via reflectionthe laws of reflectionperformance costwhen to use reflectionunsafe package (overview)

These are the notes for Go episode 39. Raju's admin page must show any record as "field: value" lines. A type switch (episode 22) works for Order, but prints "don't know how to show main.Customer" for every new type, and a library like encoding/json could never list your types at all. So you invent reflection: a program examining its own types and values while it runs. You meet reflect.TypeOf and reflect.ValueOf, the difference between a Kind and a Type, read struct fields and tags, crash on settability and fix it with a pointer and Elem, call methods by name, learn the three laws of reflection, measure how slow reflection is, decide when to use it, and take a first look at the unsafe package.

Every program here runs as-is in the SyntaxPilot compiler (language: Go) with go run main.go. All outputs and errors are from real runs (Go 1.24.7, linux/amd64). The timing program prints a different number on every run.

Facts and sources

  • go doc reflect (Go 1.24.7): "Package reflect implements run-time reflection, allowing a program to manipulate objects with arbitrary types. The typical use is to take a value with static type interface{} and extract its dynamic type information by calling TypeOf, which returns a Type. A call to ValueOf returns a Value representing the run-time data."
  • go doc reflect.Value.CanSet: "A Value can be changed only if it is addressable and was not obtained by the use of unexported struct fields. If CanSet returns false, calling Value.Set or any type-specific setter (e.g., Value.SetBool, Value.SetInt) will panic."
  • The Laws of Reflection, Rob Pike, The Go Blog, 6 September 2011 (go.dev/blog/laws-of-reflection): 1. "Reflection goes from interface value to reflection object." 2. "Reflection goes from reflection object to interface value." 3. "To modify a reflection object, the value must be settable."
  • Go Proverbs, Rob Pike, Gopherfest SV, November 2015 (slides): "Clear is better than clever." "Reflection is never clear."
  • go doc unsafe: "Package unsafe contains operations that step around the type safety of Go programs. Packages that import unsafe may be non-portable and are not protected by the Go 1 compatibility guidelines."

The problem: a function for every type

package main

import "fmt"

type Order struct {
    ID     int
    Item   string
    Amount int
}
type Customer struct {
    Name string
    City string
}

// print any record as "field: value" lines for the admin page
func show(v any) {
    switch x := v.(type) {
    case Order:
        fmt.Println("ID:", x.ID, "| Item:", x.Item, "| Amount:", x.Amount)
    default:
        fmt.Printf("don't know how to show %T\n", v)
    }
}

func main() {
    show(Order{41, "chai", 250})
    show(Customer{"Asha", "Pune"}) // a new type: another case to write
}

Output:

ID: 41 | Item: chai | Amount: 250
don't know how to show main.Customer

A type switch only handles the types listed when the code was written. Every new type (products, coupons, riders…) needs a new case, and a library can't know your types at all. We need code that asks a value, at run time (while the program runs): what type are you, what fields do you have, what's in them? That is reflection.

reflect.TypeOf and reflect.ValueOf (the airport X-ray)

At airport security In Go
an X-ray sees inside any bag, without knowing what's in it reflect.TypeOf(x), reflect.ValueOf(x)
"a car" vs "a Maruti Swift": category vs exact model Kind vs Type
labels on a parcel: FRAGILE, THIS SIDE UP struct tags
  • reflect.TypeOf(x) returns a reflect.Type: the exact type (main.Rupees, []int, *main.Order).
  • reflect.ValueOf(x) returns a reflect.Value: the data, with getters Int(), String(), Float(), Bool(), Len(), Field(i) …
  • Kind (reflect.Kind) is the category: Int, String, Struct, Slice, Map, Pointer (printed ptr), Func …. There is a fixed set of kinds but endless types, so reflection code usually switches on the Kind.
package main

import (
    "fmt"
    "reflect"
)

type Rupees int

type Order struct {
    ID   int
    Item string
}

func main() {
    values := []any{42, "chai", Rupees(250),
        Order{41, "chai"}, []int{1, 2}, &Order{}}
    for _, v := range values {
        t := reflect.TypeOf(v)
        fmt.Printf("%-12v kind=%v\n", t, t.Kind())
    }
    v := reflect.ValueOf(Rupees(250))
    fmt.Println(v.Int()+1, v.Type(), v.Kind() == reflect.Int)
}

Output:

int          kind=int
string       kind=string
main.Rupees  kind=int
main.Order   kind=struct
[]int        kind=slice
*main.Order  kind=ptr
251 main.Rupees true

main.Rupees has kind int: a defined type's kind is that of its underlying type (episode 19). Value.Int() returns an int64. Calling the wrong getter panics (for example Int() on a string Value); String() is special: on a non-string it returns a description like <int Value>.

Struct fields and tags

Type.NumField() counts fields; Type.Field(i) returns a reflect.StructField (name, type, tag, IsExported()); Value.Field(i) is the field's data. Tag.Get("form") reads the value of the form key in a struct tag (episode 35).

package main

import (
    "fmt"
    "reflect"
)

type Order struct {
    ID     int    `form:"Order no"`
    Item   string `form:"Item"`
    Amount int    `form:"Amount (Rs)"`
    note   string // unexported
}
type Customer struct {
    Name string `form:"Customer"`
    City string
}

func show(x any) {
    v := reflect.ValueOf(x)
    t := v.Type()
    for i := 0; i < t.NumField(); i++ {
        f := t.Field(i)
        label := f.Tag.Get("form")
        if label == "" {
            label = f.Name
        }
        if f.IsExported() {
            fmt.Printf("%s: %v | ", label, v.Field(i))
        }
    }
    fmt.Println()
}

func main() {
    show(Order{41, "chai", 250, "extra hot"})
    show(Customer{"Asha", "Pune"}) // no new code needed
}

Output:

Order no: 41 | Item: chai | Amount (Rs): 250 | 
Customer: Asha | City: Pune | 
  • Customer needed no new code; City has no tag, so it falls back to its field name.
  • The unexported note field is skipped with IsExported() (lowercase = not exported, episode 19). Reading an unexported field's value with Interface() would panic.
  • This is how encoding/json reads json:"..." tags and how fmt prints %v.

Passing a non-struct crashes:

package main

import (
    "fmt"
    "reflect"
)

type Order struct {
    ID     int    `form:"Order no"`
    Item   string `form:"Item"`
    Amount int    `form:"Amount (Rs)"`
    note   string // unexported
}
type Customer struct {
    Name string `form:"Customer"`
    City string
}

func show(x any) {
    v := reflect.ValueOf(x)
    t := v.Type()
    for i := 0; i < t.NumField(); i++ {
        f := t.Field(i)
        label := f.Tag.Get("form")
        if label == "" {
            label = f.Name
        }
        if f.IsExported() {
            fmt.Printf("%s: %v | ", label, v.Field(i))
        }
    }
    fmt.Println()
}

func main() {
    show(Order{41, "chai", 250, "extra hot"})
    show(42) // not a struct
}

Output:

Order no: 41 | Item: chai | Amount (Rs): 250 | 
panic: reflect: NumField of non-struct type int

goroutine 1 [running]:
reflect.(*rtype).NumField(0x4dd6f8?)
    /usr/local/go1.24.7/src/reflect/type.go:782 +0x59
main.show({0x49ea60?, 0x4dcfb8?})
    /tmp/x/main.go:22 +0x112
main.main()
    /tmp/x/main.go:37 +0x7d
exit status 2

Check v.Kind() == reflect.Struct first.

Changing values: CanSet and Elem (photocopy vs original)

package main

import (
    "fmt"
    "reflect"
)

type Order struct {
    ID     int
    Amount int
}

func main() {
    o := Order{41, 250}
    v := reflect.ValueOf(o) // a copy of o
    fmt.Println("settable?", v.Field(1).CanSet())
    v.Field(1).SetInt(300)
    fmt.Println(o)
}

Output:

settable? false
panic: reflect: reflect.Value.SetInt using unaddressable value

goroutine 1 [running]:
reflect.flag.mustBeAssignableSlow(0x0?)
    /usr/local/go1.24.7/src/reflect/value.go:260 +0x74
reflect.flag.mustBeAssignable(...)
    /usr/local/go1.24.7/src/reflect/value.go:247
reflect.Value.SetInt({0x49ba00?, 0xc00010aee8?, 0xc00010af20?}, 0x12c)
    /usr/local/go1.24.7/src/reflect/value.go:2135 +0x45
main.main()
    /tmp/x/main.go:17 +0x133
exit status 2

ValueOf(o) received a copy of o (Go passes everything by value, episode 9), so changing it would change nothing, and reflect refuses: the value is not addressable (reachable through a pointer).

At the office In Go
writing on a photocopy: the original doesn't change reflect.ValueOf(o): CanSet() == false
the cupboard where the original is kept reflect.ValueOf(&o): a pointer
open the cupboard and edit the real form .Elem(): the value the pointer points to, settable
package main

import (
    "fmt"
    "reflect"
)

type Order struct {
    ID     int
    Amount int
    note   string
}

func main() {
    o := Order{41, 250, ""}
    v := reflect.ValueOf(&o).Elem() // the pointer, then what it points to
    fmt.Println(v.Kind(), v.Field(1).CanSet(), v.Field(2).CanSet())
    v.Field(1).SetInt(300)
    v.FieldByName("ID").Set(reflect.ValueOf(99))
    fmt.Println(o)

    x := 5
    reflect.ValueOf(&x).Elem().SetInt(7)
    fmt.Println(x)
}

Output:

struct true false
{99 300 }
7
  • Elem() follows a pointer (or an interface) to the value inside.
  • A value is settable only if it is addressable and not reached through an unexported field.
  • SetInt, SetString, SetFloat, Set(reflect.ValueOf(x)): the new value must have the right type, or it panics.
  • FieldByName("ID") finds a field by name (an invalid Value if there is none).

Setting an unexported field:

package main

import "reflect"

type Order struct{ note string }

func main() {
    o := Order{}
    reflect.ValueOf(&o).Elem().Field(0).SetString("hot")
}

Output:

panic: reflect: reflect.Value.SetString using value obtained using unexported field

goroutine 1 [running]:
reflect.flag.mustBeAssignableSlow(0x70?)
    /usr/local/go1.24.7/src/reflect/value.go:257 +0xb4
reflect.flag.mustBeAssignable(...)
    /usr/local/go1.24.7/src/reflect/value.go:247
reflect.Value.SetString({0x470cc0?, 0xc00010af20?, 0x0?}, {0x47e4fb, 0x3})
    /usr/local/go1.24.7/src/reflect/value.go:2215 +0x48
main.main()
    /tmp/x/main.go:9 +0x7f
exit status 2

Calling methods with reflection

package main

import (
    "fmt"
    "reflect"
)

type Order struct{ Qty, Price int }

func (o Order) Total() int { return o.Qty * o.Price }

func (o Order) WithTip(tip int) string {
    return fmt.Sprint(o.Total()+tip, " incl. tip")
}

func main() {
    v := reflect.ValueOf(Order{3, 40})
    t := v.Type()
    for i := 0; i < t.NumMethod(); i++ {
        fmt.Println("method:", t.Method(i).Name, t.Method(i).Type)
    }
    out := v.MethodByName("Total").Call(nil)
    fmt.Println(out[0].Int())
    args := []reflect.Value{reflect.ValueOf(20)}
    fmt.Println(v.MethodByName("WithTip").Call(args)[0])

    m := v.MethodByName("Discount") // no such method
    fmt.Println(m.IsValid())
}

Output:

method: Total func(main.Order) int
method: WithTip func(main.Order, int) string
120
140 incl. tip
false
  • Type.NumMethod() and Type.Method(i) list the exported methods (the method set, episode 20). For a value receiver type, the method's type shows the receiver as the first parameter.
  • Value.MethodByName(name) returns the method as a Value; Call([]reflect.Value) runs it and returns the results as []reflect.Value.
  • A missing method gives an invalid (zero) Value: check IsValid(), because calling it panics:
package main

import "reflect"

type Order struct{ Qty int }

func main() {
    reflect.ValueOf(Order{3}).MethodByName("Discount").Call(nil)
}

Output:

panic: reflect: call of reflect.Value.Call on zero Value

goroutine 1 [running]:
reflect.flag.mustBe(...)
    /usr/local/go1.24.7/src/reflect/value.go:221
reflect.Value.Call({0x0?, 0x0?, 0x0?}, {0x0?, 0x0?, 0xc000102060?})
    /usr/local/go1.24.7/src/reflect/value.go:366 +0x111
main.main()
    /tmp/x/main.go:8 +0x91
exit status 2

The compiler can check none of this: wrong names and wrong argument types become panics at run time.

The three laws of reflection

package main

import (
    "fmt"
    "reflect"
)

func main() {
    var price float64 = 249.5

    // law 1: interface value -> reflection object
    v := reflect.ValueOf(price)
    fmt.Println(v.Type(), v.Float())

    // law 2: reflection object -> interface value
    back := v.Interface().(float64)
    fmt.Println(back + 0.5)

    // law 3: to modify, the value must be settable
    p := reflect.ValueOf(&price).Elem()
    p.SetFloat(199)
    fmt.Println(price, v.CanSet(), p.CanSet())
}

Output:

float64 249.5
250
199 false true
  1. Interface value → reflection object. reflect.ValueOf takes an any; your value is first stored in an interface, which carries its dynamic type (episode 21), and reflect reads it from there.
  2. Reflection object → interface value. v.Interface() gives back an any; a type assertion (episode 22) recovers the concrete type.
  3. To modify a reflection object, the value must be settable. Pass a pointer and use Elem().

The cost

package main

import (
    "fmt"
    "reflect"
    "time"
)

type Order struct{ ID, Amount int }

func main() {
    o := Order{41, 250}
    const n = 10_000_000
    sum := 0

    start := time.Now()
    for i := 0; i < n; i++ {
        sum += o.Amount // direct field access
    }
    direct := time.Since(start)

    start = time.Now()
    v := reflect.ValueOf(o)
    for i := 0; i < n; i++ {
        sum += int(v.FieldByName("Amount").Int()) // found by name
    }
    slow := time.Since(start)
    ratio := int(slow / max(direct, 1))
    fmt.Println(sum > 0, "reflection is about", ratio, "times slower")
}

Output (one real run; the values change on every run):

true reflection is about 357 times slower

On our test runs reflection was between about 90 and 270 times slower than direct access (it varies by run and machine). Direct code compiles to a few machine instructions; reflection looks names up and checks types while running, and allocates. Looking things up once outside the loop (e.g. v.FieldByIndex with a cached index, or a cached StructField) helps a lot.

When to use reflection

Use it Avoid it
libraries that must handle any type: encoding/json, fmt, log/slog, ORMs when an interface (episode 21) or generics (episode 30) would do
reading struct tags: forms, validation, config loading in hot loops (code that runs millions of times) without caching
tools: printers, deep comparison (reflect.DeepEqual) to "save typing" in ordinary business code

"Clear is better than clever. Reflection is never clear." (Go Proverbs)

The unsafe package (overview)

package main

import (
    "fmt"
    "unsafe"
)

type A struct {
    ok   bool  // 1 byte
    id   int64 // 8 bytes
    flag bool  // 1 byte
}
type B struct {
    id       int64
    ok, flag bool
}

func main() {
    fmt.Println(unsafe.Sizeof(A{}), unsafe.Sizeof(B{}))
    fmt.Println(unsafe.Offsetof(A{}.id), unsafe.Alignof(int64(0)))

    x := int32(-1)
    u := *(*uint32)(unsafe.Pointer(&x)) // read the same bytes as another type
    fmt.Println(u)
}

Output:

24 16
8 8
4294967295
  • unsafe.Sizeof gives a type's size in bytes, Offsetof where a field starts, Alignof its alignment: the byte boundary a value must start on (8 for int64 here).
  • Padding: in A, the int64 must start at a multiple of 8, so 7 unused bytes follow the first bool, and the struct is rounded up to 24 bytes. Putting big fields first (B) gives 16 bytes.
  • unsafe.Pointer converts between pointer types, so you can read the same bits as another type: int32(-1) read as uint32 is 4294967295. The type system no longer protects you, and such code is not covered by the Go 1 compatibility promise (episode 2). Use it only for low-level code that truly needs it.

Mini project: a tag validator

Validate(x any) loops over the fields of any struct (or pointer to struct) and applies validate:"required" (non-empty string) and validate:"min=N" (int at least N) rules; a non-struct returns an error instead of panicking.

Solution
package main

import (
    "fmt"
    "reflect"
    "strconv"
    "strings"
)

type Order struct {
    Name string `validate:"required"`
    Qty  int    `validate:"min=1"`
    Note string
}

func Validate(x any) ([]string, error) {
    v := reflect.ValueOf(x)
    if v.Kind() == reflect.Pointer {
        v = v.Elem()
    }
    if v.Kind() != reflect.Struct {
        return nil, fmt.Errorf("validate: want a struct, got %v", v.Kind())
    }
    var problems []string
    t := v.Type()
    for i := 0; i < t.NumField(); i++ {
        f, rule := t.Field(i), t.Field(i).Tag.Get("validate")
        fv := v.Field(i)
        switch {
        case rule == "required" && fv.Kind() == reflect.String && fv.String() == "":
            problems = append(problems, f.Name+" is required")
        case strings.HasPrefix(rule, "min=") && fv.Kind() == reflect.Int:
            min, err := strconv.Atoi(strings.TrimPrefix(rule, "min="))
            if err != nil {
                return nil, fmt.Errorf("validate: bad rule %q on %s", rule, f.Name)
            }
            if fv.Int() < int64(min) {
                problems = append(problems, fmt.Sprintf("%s must be at least %d", f.Name, min))
            }
        }
    }
    return problems, nil
}

func main() {
    fmt.Println(Validate(Order{Name: "chai", Qty: 2}))
    fmt.Println(Validate(Order{Qty: 0}))
    fmt.Println(Validate(&Order{Name: "samosa", Qty: 1}))
    fmt.Println(Validate(42))
}

Output:

[] <nil>
[Name is required Qty must be at least 1] <nil>
[] <nil>
[] validate: want a struct, got int

Common mistakes (and the real messages)

Mistake Real message / result Why Fix
a type switch for every type don't know how to show main.Customer only listed types reflect over fields
NumField on a non-struct panic: reflect: NumField of non-struct type int not a struct check Kind()
setting through ValueOf(o) panic: reflect: reflect.Value.SetInt using unaddressable value a copy ValueOf(&o).Elem()
setting an unexported field panic: reflect: reflect.Value.SetString using value obtained using unexported field lowercase = private export it, or don't
calling a missing method panic: reflect: call of reflect.Value.Call on zero Value no such method check IsValid()
comparing Type instead of Kind main.Rupees != int Type is exact t.Kind() == reflect.Int
reflection in a hot loop ~100× slower run-time lookups cache, or avoid

Practice

  1. (Homework) Build the tag validator (solution above).
  2. (Homework) Print any struct as a table of name, value and type.
  3. (Homework) Reorder a struct's fields to save padding; check with unsafe.Sizeof.
  4. (Homework) Compare reflection vs direct access speed on your machine (the SPEED program above).
Solution 2
package main

import (
    "fmt"
    "reflect"
)

type Product struct {
    Name  string
    Price int
    Veg   bool
}

func table(x any) {
    v := reflect.ValueOf(x)
    if v.Kind() != reflect.Struct {
        fmt.Println("not a struct:", v.Kind())
        return
    }
    for i := 0; i < v.NumField(); i++ {
        f := v.Type().Field(i)
        fmt.Printf("| %-6s | %-6v | %-6s |\n", f.Name, v.Field(i), f.Type)
    }
}

func main() {
    table(Product{"Thali", 180, true})
    table(3.5)
}

Output:

| Name   | Thali  | string |
| Price  | 180    | int    |
| Veg    | true   | bool   |
not a struct: float64
Solution 3
package main

import (
    "fmt"
    "unsafe"
)

type Before struct {
    Veg   bool
    Price int64
    Spicy bool
    Stock int32
    Hot   bool
}

type After struct { // biggest fields first
    Price int64
    Stock int32
    Veg   bool
    Spicy bool
    Hot   bool
}

func main() {
    fmt.Println(unsafe.Sizeof(Before{}), unsafe.Sizeof(After{}))
}

Output:

32 16

The bools between bigger fields each forced padding; biggest-first packs them together.

Quick quiz

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

type Celsius float64
var c Celsius = 36.6
t := reflect.TypeOf(c)
fmt.Println(t, t.Kind())

A. main.Celsius float64 · B. float64 float64 · C. main.Celsius main.Celsius · D. Celsius struct

Answer

A. The Type is the exact defined type; the Kind is the category of its underlying type.

2. Why does reflect.ValueOf(x).SetInt(5) panic for an int variable x?

Answer

ValueOf(x) holds a copy, which is not addressable. Use reflect.ValueOf(&x).Elem().SetInt(5).

3. What is the Kind of reflect.TypeOf(&Order{})?

Answer

ptr (reflect.Pointer); .Elem() gives the struct type.

4. Which law says you need a pointer to modify a value?

Answer

The third: to modify a reflection object, the value must be settable.

Interview questions

  1. What is reflection, and how does encoding/json use it? Examining types and values at run time; JSON walks struct fields and reads their json tags.
  2. Kind vs Type? Type is the exact type (main.Rupees); Kind is its category (int).
  3. Why can't you set a field through reflect.ValueOf(s)? It's a copy, not addressable; pass a pointer and use Elem().
  4. Can reflection read or set unexported fields? It can see them (Type.Field), but not set them, and Interface() on them panics.
  5. State the three laws of reflection. Interface → reflection object; reflection object → interface; to modify, the value must be settable.
  6. What are the downsides of reflection? Slower, no compile-time checks (panics instead), harder to read.
  7. When would you choose generics over reflection? When the set of operations is known and can be expressed with type parameters and constraints; it's type-safe and fast.
  8. What is struct padding? Unused bytes the compiler inserts so fields are aligned; ordering fields by size reduces it.
  9. What does unsafe.Pointer allow, and why is it risky? Converting between arbitrary pointer types; it bypasses type safety and the Go 1 compatibility promise.

Glossary

Term Meaning Example
Reflection a program examining its own types and values at run time reflect.TypeOf(x)
Run time / compile time while the program runs / while it is built type switch cases are fixed at compile time
reflect package Go's reflection package import "reflect"
reflect.TypeOf the dynamic type of a value main.Order
reflect.ValueOf a reflect.Value holding the data v.Int()
reflect.Type describes a type: name, kind, fields, methods t.NumField()
reflect.Value holds a value and lets you read or set it v.Field(0)
Kind the category of a type reflect.Struct
Type (exact) the precise type main.Rupees
Underlying type the type a defined type is based on int for Rupees
Dynamic type the concrete type stored in an interface Order inside an any
NumField / Field(i) number of struct fields / field i t.Field(0).Name
StructField a field's name, type, tag f.Tag
Struct tag a label on a field, read by reflection `form:"Order no"`
Tag.Get read one key from a tag f.Tag.Get("form")
IsExported is the field name capitalised? f.IsExported()
Settable / CanSet can this Value be changed? false for a copy
Addressable reachable through a pointer, so it can be changed ValueOf(&o).Elem()
Elem the value a pointer (or interface) points to v.Elem()
SetInt, SetString, Set change a settable value v.SetInt(300)
FieldByName find a field by its name v.FieldByName("ID")
NumMethod / Method(i) count / get exported methods t.Method(0).Name
MethodByName find a method by name v.MethodByName("Total")
Call call a function or method Value m.Call(nil)
IsValid does this Value hold anything? false for a missing method
Zero Value (reflect) an invalid, empty reflect.Value reflect.Value{}
Interface() turn a Value back into an any v.Interface().(float64)
Laws of reflection Rob Pike's three rules (2011) see above
Hot loop code that runs a huge number of times a loop of 10 million
reflect.DeepEqual compare two values deeply slices, maps
unsafe package operations that step around type safety unsafe.Sizeof
unsafe.Sizeof size of a type in bytes 24
unsafe.Offsetof where a field starts in its struct 8
unsafe.Alignof required alignment of a type 8 for int64
Alignment the byte boundary a value must start on multiple of 8
Padding unused bytes added for alignment 7 bytes after a bool
unsafe.Pointer a pointer that converts to any pointer type (*uint32)(unsafe.Pointer(&x))
Go Proverbs short sayings about Go by Rob Pike (2015) "Reflection is never clear."

Summary

  • A type switch only knows listed types; reflection examines types and values at run time.
  • TypeOf gives the exact Type; Kind() its category. ValueOf reads the data.
  • Struct fields come with names, types and tags (Tag.Get); check Kind() == Struct first.
  • To change a value: ValueOf(&x).Elem(); only addressable, exported values are settable.
  • MethodByName + Call call methods by name; check IsValid().
  • Three laws: interface → reflection object → interface; to modify, it must be settable.
  • Reflection is slow and unchecked: libraries use it; everyday code prefers interfaces and generics.
  • unsafe steps around type safety: Sizeof, Offsetof, Alignof, Pointer; field order changes padding.

Next episode: Testing basics: the testing package, _test.go files, TestXxx, t.Error vs t.Fatal, go test -v -run, table-driven tests, subtests, t.Helper, t.Cleanup, t.TempDir, and coverage.