System Design

G22

Reflection and unsafe

reflect and unsafe remove compile-time checks. Libraries use them, so you must read them, and normal code rarely needs them. Here are the rules, recorded from real runs, and the measured cost of each.

Not startedSaved in this browser only.
  1. 1reflect sees what an interface holds. To change a value, pass a pointer and call Elem.
  2. 2Reflect at setup and store the result. encoding/json walks a type once and reuses a function for every later call.
  3. 3unsafe.String shares memory. If the bytes change, the string changes, also inside a map.
  4. 4Use generics when you know the shape at compile time. Use reflect only for types you cannot name, and unsafe only with a profile.
G22
    A

    The trap

    one line saves one copy
    a map key with no copygo
    package main
    
    import (
      "fmt"
      "unsafe"
    )
    
    func main() {
      m := map[string]int{}
      b := []byte("alice")
      key := unsafe.String(&b[0], len(b))1 // no copy
      m[key] = 1
    
      b[0] = 'z'2 // reuse the buffer for the next record
    
      fmt.Println(len(m))
      fmt.Println(m["alice"], m["zlice"]3)
      for k, v := range m {
        fmt.Println(k, v)
      }
    }
    1. 1The string points at the bytes of b. No copy happens.
    2. 2Changes the string too, because a string header points at the same memory.
    3. 3The map hashed "alice", and the key now reads "zlice". The entry sits where neither lookup goes.
    output, with unsafe.Stringshell
    1
    0 0
    zlice 1
    output, with string(b)shell
    1
    1 0
    alice 1
    • The map holds 1 entry, and no lookup can reach it.
    • The race detector and go vet report nothing here. One goroutine does all of this.
    • The fix is the copy. Panel I shows that the compiler often removes it for you.

    unsafe.String shares the bytes. If the buffer changes after the string goes into a map, the key cannot be found by any lookup.

    B

    The model: Type and Value

    reflect/value.go, Go 1.27
    var x any = usertype word*abi.Typedata wordunsafe.Pointerreflect.Typename, kind, fieldsreflect.Valuetype + pointer + flagsflagAddr: settable?one per typeread-only, sharedKindthe underlying shapeValueOf(x)A copyNo way back to x, so Set panics.ValueOf(&x).Elem()The variable itselfAddressable, so Set reaches x.
    • A call to ValueOf converts its argument to an interface, so the Value starts from a copy.
    • A pointer is copied too, but it still leads to the original. Elem follows it.

    An interface holds a type word and a data word. TypeOf reads the first. ValueOf keeps both, and a flag says if the data can change.

    C

    The rules: three questions

    what to ask
    askcall
    What is it called?TypeOf(x)
    What shape is it?t.Kind()
    What does it hold?ValueOf(x)
    What is behind it?v.Elem()
    Can I change it?v.CanSet()
    Back to a Go valuev.Interface()

    Switch on Kind, not on Type. There are 26 kinds and no limit on named types.

    Type says what it is called, Kind says what shape it has, and Value holds the data.

    D

    The rules: settable values

    recorded: each row is one real Set
    what you holdcodeCanAddrCanSetwhat Set did
    A plain variableValueOf(x)falsefalseusing unaddressable value
    The pointer itselfValueOf(&x)falsefalseusing unaddressable value
    Through the pointerValueOf(&x).Elem()truetruewrote the original
    Field of a struct copyValueOf(s).Field(0)falsefalseusing unaddressable value
    Field through a pointerValueOf(&s).Elem().Field(0)truetruewrote the original
    Unexported field through a pointerValueOf(&s).Elem().Field(1)truefalseusing value obtained using unexported field
    Element of an array copyValueOf(arr).Index(0)falsefalseusing unaddressable value
    Element of a sliceValueOf(slice).Index(0)truetruewrote the original
    Map valueValueOf(m).MapIndex(ValueOf("a"))falsefalseusing unaddressable value

    A slice header holds a pointer, so its elements are addressable even when the header is a copy. A map value is never addressable: a map can move its entries.

    A Value is settable if it is addressable and I reached it through exported names. A copy never is. A slice element is, because the header points at the array.

    E

    Walk a struct

    tested
    describego
    // Field is one exported field of a struct.
    type Field struct {
      Name, Type, Kind, Tag string
    }
    
    // Describe lists the exported fields of a struct or a struct pointer.
    func Describe(v any) ([]Field, error) {
      t := reflect.TypeOf(v)
      if t == nil1 {
        return nil, errors.New("describe: nil has no type")
      }
      if t.Kind() == reflect.Pointer2 {
        t = t.Elem()
      }
      if t.Kind() != reflect.Struct {
        return nil, fmt.Errorf("describe: %s is not a struct", t)
      }
      var out []Field
      for f := range t.Fields()3 {
        if !f.IsExported() {
          continue
        }
        out = append(out, Field{
          Name: f.Name,
          Type: f.Type.String(),
          Kind: f.Type.Kind().String(),
          Tag:  f.Tag.Get("json")4,
        })
      }
      return out, nil
    }
    1. 1A nil interface has no type word. Each method call on this nil would panic.
    2. 2Accept both forms. Elem on a type gives the type it points to.
    3. 3An iterator: Go 1.26. Older code loops to NumField and calls Field(i).
    4. 4A tag is a plain string. Get parses it on each call, so store the result.

    I check for nil, follow one pointer, confirm the kind is struct, and range over the fields. Each check replaces a panic.

    F

    Set fields from tags

    tested
    fillgo
    // Fill sets each field of the struct at dst that has an env tag.
    // lookup returns the text for a tag, or false when there is none.
    func Fill(dst any, lookup func(string) (string, bool)) error {
      p := reflect.ValueOf(dst)
      if p.Kind() != reflect.Pointer || p.IsNil()1 {
        return fmt.Errorf("fill: need a non-nil pointer, got %T", dst)
      }
      v := p.Elem()
      if v.Kind() != reflect.Struct {
        return fmt.Errorf("fill: %s is not a struct", v.Type())
      }
      for f, fv := range v.Fields()2 {
        key, ok := f.Tag.Lookup("env")3
        if !ok {
          continue
        }
        if !fv.CanSet()4 {
          return fmt.Errorf("fill: %s is not exported", f.Name)
        }
        text, ok := lookup(key)
        if !ok {
          continue
        }
        switch fv.Kind()5 {
        case reflect.String:
          fv.SetString(text)
        case reflect.Int, reflect.Int64:
          n, err := strconv.ParseInt(text, 10, 64)
          if err != nil {
            return fmt.Errorf("fill: %s: %w", key, err)
          }
          fv.SetInt(n)
        case reflect.Bool:
          b, err := strconv.ParseBool(text)
          if err != nil {
            return fmt.Errorf("fill: %s: %w", key, err)
          }
          fv.SetBool(b)
        default:
          return fmt.Errorf("fill: %s: no rule for %s", key, fv.Kind())
        }
      }
      return nil
    }
    1. 1A struct passed by value gives a copy. Return an error here, not a panic later.
    2. 2Yields the StructField and the field Value together: Go 1.26.
    3. 3Lookup separates a missing tag from an empty one. Get cannot.
    4. 4A tagged unexported field would panic on Set.
    5. 5One case per kind, so a named type such as type Port int works too.

    A tag-driven loader needs a pointer, a CanSet check and a switch on Kind. Every mistake appears at run time, so tests must cover it.

    G

    How encoding/json uses reflect

    encoding/json/v2 source, Go 1.27
    json.Marshal(v)reflect.ValueOf(v)lookup by typesync.Map, keyed on Typemiss: oncebuild the marshalerwalk fields, parse tags, use Kindhit: every callcall the stored functionfield by index, no tags, no namesstored in the map
    • Since Go 1.27, encoding/json runs on the v2 implementation. The cache is a sync.Map from reflect.Type to a pair of functions.
    • The first call for a type pays for the walk. If two goroutines race on it, both build and one result stays.
    • Marshal needs an addressable value, so it copies a non-pointer into new memory first. Pass a pointer and that copy goes away (panel I).
    • The walk skips unexported fields. Reflect refuses to set them, so a decode could not fill them.

    encoding/json reflects once per type and stores a function. After the first call, it follows the plan and does not read tags again.

    H

    The same plan, small

    tested against encoding/json
    encodergo
    // step writes one field. Each struct type gets one list of steps.
    type step struct {
      index int // field position, for v.Field
      key   []byte
      write func(buf []byte, v reflect.Value) []byte
    }
    
    // plans maps a reflect.Type to its []step.
    var plans sync.Map1
    
    func planFor(t reflect.Type) ([]step, error) {
      if p, ok := plans.Load(t)2; ok {
        return p.([]step), nil
      }
      p, err := buildPlan(t)
      if err != nil {
        return nil, err
      }
      stored, _ := plans.LoadOrStore(t, p)3
      return stored.([]step), nil
    }
    
    // buildPlan does the slow work once per type: it reads every field and
    // tag, and picks a writer by Kind.
    func buildPlan(t reflect.Type) ([]step, error) {
      var steps []step
      for f := range t.Fields() {
        name, ok := f.Tag.Lookup("json")4
        if !f.IsExported() || name == "-" {
          continue
        }
        if !ok {
          name = f.Name
        }
        s := step{index: f.Index[0]}
        s.key = strconv.AppendQuote(nil, name)
        s.key = append(s.key, ':')
        switch f.Type.Kind()5 {
        case reflect.String:
          s.write = func(b []byte, v reflect.Value) []byte {
            return strconv.AppendQuote(b, v.String())
          }
        case reflect.Int, reflect.Int64:
          s.write = func(b []byte, v reflect.Value) []byte {
            return strconv.AppendInt(b, v.Int(), 10)
          }
        case reflect.Bool:
          s.write = func(b []byte, v reflect.Value) []byte {
            return strconv.AppendBool(b, v.Bool())
          }
        default:
          return nil, fmt.Errorf("plan: %s: no writer", f.Type)
        }
        steps = append(steps, s)
      }
      return steps, nil
    }
    
    // Encode writes a struct as a JSON object. The plan lookup is one map
    // read, so only the first call for a type pays for the field walk.
    func Encode(x any) ([]byte, error) {
      v := reflect.ValueOf(x)
      if v.Kind() != reflect.Struct {
        return nil, fmt.Errorf("encode: %T is not a struct", x)
      }
      steps, err := planFor(v.Type())
      if err != nil {
        return nil, err
      }
      return run(steps, v), nil
    }
    
    func run(steps []step, v reflect.Value) []byte {
      buf := make([]byte, 0, 128)
      buf = append(buf, '{')
      for i, s := range steps {
        if i > 0 {
          buf = append(buf, ',')
        }
        buf = append(buf, s.key...)
        buf = s.write(buf, v.Field(s.index)6)
      }
      return append(buf, '}')
    }
    1. 1reflect.Type is comparable, so it works as a map key. Types are few and live forever, so the map cannot grow without limit.
    2. 2The common path: one read with no lock.
    3. 3Two goroutines can build a plan at once. Both use the one that was stored.
    4. 4Tags are read here, once per type, and never on the request path.
    5. 5The Kind switch runs once. Later calls go straight to the closure.
    6. 6An index is what remains of the field name. FieldByName would scan the fields on each call.

    I can write this shape in an interview: one sync.Map keyed on the type, one slice of steps, and one closure per field.

    I

    The cost, measured

    testing.B, interleaved runs
    operationplain Gowith reflectfactorallocations
    Read a field by index1.0 ns3.4 ns3×0 and 0
    Read a field by name1.0 ns46.7 ns45×0 and 0
    Write a field1.2 ns3.4 ns3×0 and 0
    Call a function1.1 ns199 ns174×0 and 2
    Search 100 ints38.5 ns4,391 ns114×0 and 101
    encode one struct, 4 fieldstimeallocations
    By hand, no reflection121 ns1
    Small encoder, stored plan227 ns2
    Small encoder, plan rebuilt on each call1,143 ns18
    json.Marshal(&v)311 ns1
    json.Marshal(v)428 ns3
    bytes to stringtimeallocationsstatus
    string(b), 32 bytes19.4 ns1Copy
    unsafe.String, 32 bytes1.4 ns0Shared memory
    m[string(b)]11.6 ns0Compiler skips the copy
    m[unsafe view]11.5 ns0No gain
    • Rebuilding the plan on each call costs 5 times the stored plan. That is the gain from the cache in panel H.
    • The compiler already avoids the copy in m[string(b)], in comparisons, and in concatenation. Check before you add unsafe.
    • json.Marshal does more than the small encoder: escaping, nested types, marshaler methods. The two are not direct rivals.

    Reflect costs about 3 times on a field and about 174 times on a call. Interface conversions allocate, so the Contains loop costs about 114 times.

    J

    What generics replaced

    tested
    genericsgo
    // ContainsAny is the shape from before generics. Each mistake waits for
    // run time, and each element costs an interface conversion.
    func ContainsAny(list, x any) bool1 {
      v := reflect.ValueOf(list)
      for i := range v.Len() { // panics if list is not a slice
        if reflect.DeepEqual(v.Index(i).Interface()2, x) {
          return true
        }
      }
      return false
    }
    
    // Contains is the same function with a type parameter. The compiler
    // checks the element type and comparability at each call.
    func Contains[T comparable]3(list []T, x T) bool {
      for _, v := range list {
        if v == x {
          return true
        }
      }
      return false
    }
    1. 1Accepts anything. ContainsAny([]int{2}, int64(2)) compiles and returns false.
    2. 2One allocation per element, because each int must go into an interface.
    3. 3A wrong call is a compile error. The standard form is slices.Contains.

    If I can write the shape as a type parameter, the compiler checks it and the loop allocates nothing.

    K

    Old form, new form

    checked against each release's notes
    beforenowsince
    sort.Sliceslices.SortFunc1.21
    reflect.DeepEqual on slicesslices.Equal1.21
    v.MapKeys()maps.Keys1.23
    atomic.Valueatomic.Pointer[T]1.19
    TypeOf((*T)(nil)).Elem()TypeFor[T]()1.22
    v.Interface().(T)reflect.TypeAssert[T](v)1.25

    Still reflection: encoders, field walks, tags, fmt, and anything that meets a type at run time.

    Generics replaced reflection over shapes. Reflection over field names stays, because no type parameter can list a struct's fields.

    L

    The rules: unsafe.Pointer

    the unsafe package documentation, Go 1.27
    patternformconditionstatus
    1. Reinterpret a value(*T2)(unsafe.Pointer(p))T2 is no larger than T1, and the layouts match.Layouts match
    2. Print an addressuintptr(unsafe.Pointer(p))The integer never goes back to a pointer.Approved
    3. Pointer arithmeticunsafe.Add(p, n)The result stays inside the same allocation. One past the end is invalid.Same allocation
    4. System call argumentsyscall.Syscall(n, uintptr(unsafe.Pointer(p)), ...)The conversion sits in the call expression itself.In the call
    5. reflect resultunsafe.Pointer(v.Pointer())Convert in the same expression. Prefer v.UnsafePointer.Same expression
    6. Header Data fieldhdr.DataDeprecated since Go 1.21. Use the functions in panel M.Deprecated
    Store a uintptr, convert lateru := uintptr(p); unsafe.Pointer(u + 8)The object can move or die between the two lines.Not approved
    Point one past the endunsafe.Add(p, unsafe.Sizeof(s))Unlike C, Go treats this as invalid.Not approved

    There are six valid patterns. A uintptr is a number and not a reference, so the garbage collector ignores it. Convert back in one expression.

    M

    unsafe.String and unsafe.Slice

    tested
    viewsgo
    // BytesView returns b as a string with no copy. The caller must not
    // change b while the string is in use.
    func BytesView(b []byte) string {
      return unsafe.String(unsafe.SliceData(b), len(b))1
    }
    
    // StringView returns s as a byte slice with no copy. The caller must
    // never write to the result: string memory can be read-only.
    func StringView(s string) []byte {
      return unsafe.Slice(unsafe.StringData(s), len(s))2
    }
    
    // Float64Bits reads the bits of f as a uint64. Both types have the same
    // size, so this is valid pattern 1. Prefer math.Float64bits.
    func Float64Bits(f float64) uint64 {
      return *(*uint64)(unsafe.Pointer(&f))3
    }
    
    // Second reads the element after p in an array. The result must stay
    // inside the same allocation.
    func Second(p *[2]int64) int64 {
      return *(*int64)(unsafe.Add(unsafe.Pointer(p), unsafe.Sizeof(p[0]))4)
    }
    1. 1Go 1.20. The contract: b does not change while the string lives. Nothing checks it.
    2. 2A write to this slice can crash, because string data may sit in read-only memory.
    3. 3Pattern 1, and the body of math.Float64bits.
    4. 4Pattern 3. unsafe.Add arrived in Go 1.17 and keeps the pointer type all the way.

    These four functions build and take apart slices and strings with no knowledge of the header layout. I document who owns the memory.

    N

    What catches a mistake

    recorded from real builds
    mistakeplain buildwith -race
    Convert *int64 to a pointer to a larger structRunsconverted pointer straddles multiple allocations
    Convert a byte address to a pointer type at an odd addressRunsmisaligned pointer conversion
    unsafe.Add moves out of the allocationRunspointer arithmetic result points to invalid allocation
    • go vet reports a stored uintptr: possible misuse of unsafe.Pointer.
    • Nothing reports the trap in panel A. The memory stays valid, and only the meaning changes.
    • The check is best effort. The runtime source names a gap: a range that covers an allocation with neither end inside it.

    go test -race turns on checkptr, which checks each unsafe conversion at run time. A clean run proves nothing about the paths it did not take.

    O

    Padding and field order

    recorded output
    paddinggo
    package main
    
    import (
      "fmt"
      "unsafe"
    )
    
    type Loose struct {
      OK   bool
      ID   int64
      Kind uint8
      N    int32
      Code int16
    }
    
    type Tight struct {
      ID   int64
      N    int32
      Code int16
      OK   bool
      Kind uint8
    }
    
    func main() {
      var l Loose
      var t Tight
      fmt.Println(unsafe.Sizeof(l)1, unsafe.Alignof(l)2)
      fmt.Println(unsafe.Offsetof(l.ID)3, unsafe.Offsetof(l.N))
      fmt.Println(unsafe.Sizeof(t), unsafe.Alignof(t))
      fmt.Println(unsafe.Offsetof(t.N), unsafe.Offsetof(t.Kind))
    }
    1. 1A compile-time constant. It counts the struct and never follows a pointer.
    2. 2The largest alignment of any field: 8, from int64.
    3. 3OK takes byte 0, so ID must skip to byte 8.
    outputshell
    32 8
    8 20
    16 8
    8 15
    rulestatus
    Reorder a struct held by the million, after a profileApproved
    Keep fields in reading order everywhere elseApproved
    Mark a struct passed to host APIs with structs.HostLayoutApproved
    Reorder every struct by habitReaders pay
    Assume the layout of a struct from another packageNot approved

    Today the compiler keeps declared order. The spec does not promise that, so host APIs need the marker. Sizes are for 64-bit systems.

    Each field sits at a multiple of its alignment, and the size rounds up to the largest alignment. Sort large to small and the gaps go.

    P

    See it: 120 field orders

    recorded with reflect.StructOf
    struct fields, in order:
    +0+1+2+3+4+5+6+7081624OKIDKindNCode

    32 bytes

    16 bytes of data, 16 of padding.

    1 million elements: 32 MB in a slice.

    The 120 orders range from 16 to 32 bytes.

    • field
    • padding
    • not used by this order
    • Press a field to move it one place to the left. Each state is a real type that the runtime built.
    • The size matches unsafe.Sizeof on the compiled Tight and Loose structs. A test asserts this.

    The same five fields take from 16 to 32 bytes. In a slice of 1 million, that is 16 MB for nothing.

    Q

    When to avoid both

    per situation
    situationusestatus
    Encode, decode or print a type you cannot namereflect, or a library built on itApproved
    Read struct tags at startup, oncereflectApproved
    Compare in a testreflect.DeepEqualApproved
    The same function for several element typesA type parameterApproved
    A few known behavioursAn interface or a type switchApproved
    A wire format on a hot pathGenerated code, with no reflection at run timeApproved
    Zero-copy parse where a profile shows the copy, and the input stays fixedunsafe.StringWith a profile
    Business rules that dispatch on a field namereflectNot approved
    Reach an unexported field of another packageunsafeBreaks on upgrade
    Avoid an allocation that no profile showsunsafeNot approved

    I use reflect inside libraries and at startup. I use unsafe only with a profile, a test, and a comment that names the memory owner.

    R

    New in recent Go

    checked against each release's notes
    sincewhat changedwhat it means here
    1.17unsafe.Add and unsafe.Slice.Arithmetic and slicing with no uintptr in your code.
    1.18Generics. reflect.Pointer and PointerTo as new names. Value.UnsafePointer.Most reflection over shapes can go.
    1.20unsafe.String, StringData and SliceData. Value.SetZero, Grow, Comparable and Equal.Build a string or a slice with no header types.
    1.21ValueOf no longer forces its argument to the heap. Value.Clear. SliceHeader and StringHeader deprecated.Field reads through reflect can stay allocation-free.
    1.22reflect.TypeFor. PtrTo deprecated. Value.IsZero matches the == operator on negative zero.TypeFor names an interface type with no pointer trick.
    1.23Value.Seq and Seq2, Type.CanSeq, reflect.SliceAt. structs.HostLayout.Range over any rangeable Value.
    1.24The omitzero JSON tag option.Drops a zero time.Time, which omitempty keeps.
    1.25reflect.TypeAssert. encoding/json/v2 as an experiment.Get a typed value out of a Value with no extra allocation.
    1.26Type.Fields, Methods, Ins and Outs iterators. Value.Fields and Methods.The loops in panels E and F.
    1.27encoding/json/v2 and jsontext ship, and encoding/json runs on v2. Generic methods. The go fix unsafefuncs modernizer.Behaviour stays, but error text can differ. GOEXPERIMENT=nojsonv2 restores the old code for now. Reflect does not list generic methods.
    S

    In the round

    45 minutes of build, 45 minutes of talk
    whenthe momentwhat to do or say
    buildA JSON field comes back empty.Check that the field is exported. Reflect cannot set a lowercase field, and json skips it with no error.
    buildA decode changes nothing.Pass a pointer. A struct value gives json a copy that it cannot set, so it returns an error.
    buildTwo endpoints repeat a decode and validate step.Write one generic helper. Do not write a reflective validator in 45 minutes.
    buildA test compares two structs.Use reflect.DeepEqual, or == if every field is comparable.
    talk"How does json know the fields?"Panel G: one walk per type, a stored function, and a sync.Map keyed on the type.
    talk"This endpoint spends 30% in JSON. What now?"Pass pointers, reuse buffers, then consider generated code. Name unsafe last and say why.
    talk"Could you avoid this allocation with unsafe?"Yes, if a profile shows it and the bytes never change. Then show the trap from panel A.
    talk"How much does field order save?"Nothing for one struct. For millions of elements, multiply the size difference by the count.

    I keep reflection inside encoding/json. In my own code, types and interfaces do the work.

    T

    Drill

    each answer is the output of a real run

    0 of 12 known

    1. Predict the output.

      package main
      
      import (
        "fmt"
        "reflect"
      )
      
      func main() {
        x := 1
        v := reflect.ValueOf(x)
        fmt.Println(v.CanSet())
        v.SetInt(2)
        fmt.Println(x)
      }
    2. Predict the output. The value is reached through a pointer.

      package main
      
      import (
        "fmt"
        "reflect"
      )
      
      type user struct {
        Name string
        age  int
      }
      
      func main() {
        u := user{"ada", 36}
        v := reflect.ValueOf(&u).Elem()
        fmt.Println(v.Field(1).Int())
        fmt.Println(v.Field(0).CanSet(), v.Field(1).CanSet())
        v.Field(1).SetInt(37)
      }
    3. Predict the output: the type, then the kind.

      package main
      
      import (
        "fmt"
        "reflect"
        "time"
      )
      
      type Celsius float64
      
      func main() {
        for _, x := range []any{Celsius(21), 21.0, time.Second, []Celsius{}} {
          t := reflect.TypeOf(x)
          fmt.Println(t, t.Kind())
        }
      }
    4. Predict the output.

      package main
      
      import (
        "fmt"
        "reflect"
      )
      
      func main() {
        var err error
        var p *int
        fmt.Println(reflect.TypeOf(err))
        fmt.Println(reflect.TypeFor[error]())
        fmt.Println(reflect.TypeOf(p), reflect.ValueOf(p).IsNil())
        fmt.Println(reflect.ValueOf(err).Kind(), reflect.ValueOf(err).IsValid())
      }
    5. Predict the output.

      package main
      
      import (
        "fmt"
        "reflect"
      )
      
      type T struct{}
      
      func (T) Get()    {}
      func (*T) Set()   {}
      func (T) hidden() {}
      
      func main() {
        T{}.hidden()
        fmt.Println(reflect.TypeFor[T]().NumMethod())
        fmt.Println(reflect.TypeFor[*T]().NumMethod())
        _, ok := reflect.TypeFor[T]().MethodByName("Set")
        fmt.Println(ok)
      }
    6. Predict the output.

      package main
      
      import (
        "fmt"
        "math"
        "reflect"
      )
      
      func main() {
        var a []int
        b := []int{}
        fmt.Println(len(a) == len(b), reflect.DeepEqual(a, b))
        n := math.NaN()
        fmt.Println(reflect.DeepEqual(n, n))
        s := []float64{n}
        fmt.Println(reflect.DeepEqual(s, s))
      }
    7. Predict the output.

      package main
      
      import (
        "encoding/json"
        "fmt"
      )
      
      type T struct {
        A int `json:"a"`
        B int `json:"b,omitempty"`
        C int `json:"-"`
        D int `json:"-,"`
        E int
        f int
      }
      
      func main() {
        out, err := json.Marshal(T{A: 1, C: 3, D: 4, E: 5, f: 6})
        fmt.Println(string(out), err)
      }
    8. Predict the output. Both slices are empty and not nil.

      package main
      
      import (
        "encoding/json"
        "fmt"
        "time"
      )
      
      type Event struct {
        A time.Time `json:"a,omitempty"`
        B time.Time `json:"b,omitzero"`
        C []int     `json:"c,omitempty"`
        D []int     `json:"d,omitzero"`
      }
      
      func main() {
        out, err := json.Marshal(Event{C: []int{}, D: []int{}})
        fmt.Println(string(out), err)
      }
    9. Predict the output.

      package main
      
      import (
        "fmt"
        "unsafe"
      )
      
      func main() {
        big := make([]int, 1000)
        var (
          s string
          a any
          m map[int]int
          e struct{}
        )
        fmt.Println(len(big), unsafe.Sizeof(big), unsafe.Sizeof(s))
        fmt.Println(unsafe.Sizeof(a), unsafe.Sizeof(m), unsafe.Sizeof(e))
      }
    10. Predict the output.

      package main
      
      import (
        "fmt"
        "unsafe"
      )
      
      type Head struct {
        _ struct{}
        N int64
      }
      
      type Tail struct {
        N int64
        _ struct{}
      }
      
      func main() {
        fmt.Println(unsafe.Sizeof(Head{}), unsafe.Sizeof(Tail{}))
      }
    11. Predict the output.

      package main
      
      import (
        "fmt"
        "unsafe"
      )
      
      func main() {
        a := [4]int{1, 2, 3, 4}
        s := unsafe.Slice(&a[1], 2)
        fmt.Println(s, len(s), cap(s))
        s[0] = 9
        fmt.Println(a)
        t := a[1:3]
        fmt.Println(t, len(t), cap(t))
      }
    12. Predict the output. Conv is a generic method.

      package main
      
      import (
        "fmt"
        "reflect"
      )
      
      type Box struct{}
      
      func (Box) Plain() {}
      
      func (Box) Conv[T any](x T) T { return x }
      
      func main() {
        fmt.Println(Box{}.Conv(7))
        t := reflect.TypeFor[Box]()
        fmt.Println(t.NumMethod())
        for m := range t.Methods() {
          fmt.Println(m.Name)
        }
      }
    U

    Numbers to say

    measured with testing.B
    field read
    1.0 ns direct; 3.4 ns by index; 46.7 ns by name.
    call
    1.1 ns direct; 199 ns through reflect, with 2 allocations.
    json.Marshal
    311 ns with a pointer and 1 allocation; 428 ns with a value and 3.
    string(b)
    19.4 ns and 1 allocation for 32 bytes; 1.4 ns as a view.
    headers
    Slice 24 bytes, string 16, interface 16, map 8, on 64-bit.
    padding
    16 to 32 bytes for the same 5 fields.

    Go 1.27.3, 8-core Intel i9 laptop, GOMAXPROCS 16, median of 3 interleaved runs of 1 s, on a busy machine. Use these as orders of magnitude.