Common Patterns That Use Reflection in Go (JSON, ORM, DI)

Go uses reflection in JSON marshaling, ORMs, and DI containers to dynamically inspect and manipulate types at runtime.

Go uses reflection primarily in the encoding/json package for marshaling/unmarshaling, in ORMs like GORM for mapping structs to database rows, and in Dependency Injection containers like google/wire for resolving dependencies at runtime.

package main

import (
	"encoding/json"
	"fmt"
)

type User struct {
	Name string `json:"name"`
	Age  int    `json:"age"`
}

func main() {
	u := User{Name: "Alice", Age: 30}
	// encoding/json uses reflection to read struct tags and fields
	data, _ := json.Marshal(u)
	fmt.Println(string(data)) // Output: {"name":"Alice","age":30}
}