How to Use the reflect Package in Go

Use the reflect package to inspect Go types and values at runtime for dynamic programming tasks.

Use the reflect package to inspect types and values at runtime, enabling dynamic behavior like generic serialization or framework logic. Import the package and use reflect.TypeOf to get a type or reflect.ValueOf to get a value, then call methods like Kind or Field to analyze them.

package main

import (
	"fmt"
	"reflect"
)

type Person struct {
	Name string
	Age  int
}

func main() {
	p := Person{Name: "Alice", Age: 30}
	v := reflect.ValueOf(p)
	t := reflect.TypeOf(p)

	fmt.Println("Type:", t.Name())
	fmt.Println("Name Field:", v.FieldByName("Name").String())
}