Lesson 28 of 60 · Go
Reflection with the `reflect` Package
Duration: 20 minutes
Reflection Basics
This lesson explains the main concept clearly with beginner-friendly examples and background so you can learn why the code works.
reflect lets you inspect types at runtime – useful for generic libraries.
func Dump(v interface{}) {
rv := reflect.ValueOf(v)
rt := rv.Type()
fmt.Printf("type: %s, kind: %s\n", rt, rt.Kind())
for i := 0; i < rv.NumField(); i++ {
f := rt.Field(i)
val := rv.Field(i).Interface()
fmt.Printf("%s = %v\n", f.Name, val)
}
}
Setting values via reflection
func SetField(obj interface{}, name string, value interface{}) error {
rv := reflect.ValueOf(obj).Elem()
fv := rv.FieldByName(name)
if !fv.IsValid() || !fv.CanSet() { return fmt.Errorf("cannot set %s", name) }
fv.Set(reflect.ValueOf(value))
return nil
}