Panic: reflect.Value.Interface: cannot return value obtained from unexported field or method

I am trying to figure out how to access private struct fields using the reflect package.
I am currently getting this error:

panic: reflect.Value.Interface: cannot return value obtained from unexported field or method

the code that generates this error is like so:

type Foo struct {
 thisIsPrivate string
}

foo := Foo{"muh private strang"}
val := reflect.ValueOf(foo)
n := val.NumField()
t := val.Type()

for i := 0; i < n; i++ {

   k := t.Field(i).Name   // k is "thisIsPrivate"
   v := val.Field(i).Interface()   // this is what causes the panic!
}

is there any way to read the value of the private struct field “thisIsPrivate” and obtain the value “muh private strang”?

No. You can not access non exported fields. This is documented in the reflection package.

It looks like you can, using this technique: https://stackoverflow.com/questions/42664837/access-unexported-fields-in-golang-reflect/43918797#43918797

it worked for me.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.