Golang / Golang Internals and Memory Management Interview Questions
How does the reflect package work in Go and when should it be used?
The reflect package provides runtime type introspection. It lets you inspect types and values at runtime, set values dynamically, and call methods whose signatures are not known at compile time. It is the foundation of JSON marshalling, ORM field mapping, and dependency injection frameworks.
import "reflect" // reflect.TypeOf and reflect.ValueOf type Person struct { Name string `json:"name"` Age int `json:"age"` } p := Person{"Alice", 30} t := reflect.TypeOf(p) v := reflect.ValueOf(p) fmt.Println(t.Name()) // "Person" fmt.Println(t.Kind()) // struct fmt.Println(v.Field(0)) // Alice fmt.Println(v.Field(0).Type()) // string // Iterating struct fields for i := 0; i < t.NumField(); i++ { field := t.Field(i) val := v.Field(i) tag := field.Tag.Get("json") fmt.Printf("%s (%s) [json:%s] = %v\n", field.Name, field.Type, tag, val) } // Setting values via reflect â requires addressable value vp := reflect.ValueOf(&p).Elem() // dereference pointer to get addressable value vp.FieldByName("Name").SetString("Bob") fmt.Println(p.Name) // Bob // Calling methods dynamically method := v.MethodByName("String") // if Person has a String() method if method.IsValid() { results := method.Call(nil) fmt.Println(results[0]) } // reflect.DeepEqual â structural equality (used in tests) fmt.Println(reflect.DeepEqual([]int{1,2,3}, []int{1,2,3})) // true
Performance warning: reflection is 10–100× slower than direct type-specific code because it bypasses compiler optimisations. Use reflection in framework/library code that genuinely needs runtime type introspection; avoid it in hot paths. Go 1.18+ generics often replace the need for reflection in type-agnostic algorithms.
More Related questions...