Inspect reflect.Type and Value
Inspect reflect.Type and Value
Reflection lets a program inspect the concrete type and value stored in an interface at runtime. Use reflect.TypeOf for type metadata and reflect.ValueOf for operations on a value. Most code does not need reflection; it is useful for libraries that accept many unrelated types.
package main
import ( "fmt" "reflect")
type Score int
func main() { var x any = Score(42) t := reflect.TypeOf(x) v := reflect.ValueOf(x) fmt.Println(t.Name(), t.Kind(), v.Int())}The named type Score is distinct from int, but both have Kind int. Int reads a signed integer as int64; it panics on incompatible kinds. TypeOf returns the dynamic type, not the declared interface type. Check type or kind before extracting values.
Expected output:
Score int 42Inspect a known type without a value
package main
import ( "fmt" "reflect")
func main() { t := reflect.TypeFor[[]string]() fmt.Println(t.Kind(), t.Elem().Kind())}TypeFor (Go 1.22+) produces the type represented by a type argument, even if there is no value. Elem on a slice type returns its element type. Elem is not defined for every kind. Keep reflection at a narrow boundary and return ordinary typed values to callers.
Expected output:
slice stringTry it locally
Inspect a named string type Label with value "blue" and print its name, kind and text.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Reflection and unsafe 01: Inspect reflect.Type and Value
Check the lesson objective before moving on.
What distinguishes Score from int?
What does TypeOf inspect for an interface containing a value?