SoFunction
Updated on 2025-03-05

Correct use of reflection in Go


package main
 
import (
    "fmt"
    "reflect"
)
 
type T struct {
    A int
    B string
}
 
func main() {
    t := T{23, "skidoo"}
    tt := (t)
    ("t type:%v\n", tt)
    ttp := (&t)
    ("t type:%v\n", ttp)
// To set the value of t, you need to pass the address of t, not a copy of t.
// (&t) is just the value of an address, not a settable, get the t itself by dereference.
    s := (&t).Elem()
    typeOfT := ()
    for i := 0; i < (); i++ {
        f := (i)
        ("%d: %s %s = %v\n", i,
            (i).Name, (), ())
    }
}
 
// Output result
// t type:
// t type:*
// 0: A int = 23
// 1: B string = skidoo