I am trying to access a nested struct (time.Time
) within a struct using the reflect
package. However, when trying to access it as an interface
, I get the following error:
reflect.Value.Interface: cannot return value obtained from unexported field or method
How can I access this struct natively?
Example:
package main
import (
"fmt"
"reflect"
"time"
)
type Foo struct {
t time.Time
}
func main() {
foo := Foo{t: time.Now()}
v := reflect.ValueOf(foo)
f := v.FieldByName("t")
fmt.Printf("%T %v\n", f, f) // reflect.Value {13454110244426743808 1 0x5378e0}
t := f.Interface().(time.Time)
fmt.Printf("%T %v\n", t, t)
}
Go Playground: https://go.dev/play/p/O_jLStsd339