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})) // truePerformance 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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
