Contents
Dig101: dig more, simplified more and know more
Lowercase struct fields are unexported — other packages cannot name them in ordinary code. Reflection can still reach them. Here is how reflect does it from outside the defining package.
Addressable access with NewAt
NewAt builds a Value for a pointer to a value of a given type, using p as the data pointer:
1 | // reflect/value.go |
Given that, you can reflect into unexported fields. Example struct in another package:
1 | package testData |
Read field a by taking the address of eg:
1 | var eg testData.Example |
You must pass a pointer to source. Otherwise:
panic: reflect: call of reflect.Value.Elem on struct Value
Elem only applies when the Value is an interface or pointer — it returns the element or pointed-to value:
1 | // Elem returns the value that the interface v contains |
Mutating through NewAt
reflect.Value.Set (and typed setters) work on the addressable Value from NewAt, bypassing the export rule:
1 | var eg testData.Example |
Kinds must match. Changes land on the original eg.
Value (not pointer) sources
You can start from a non-pointer value using New:
1 | // New returns a Value representing a pointer to a new zero value |
Pattern:
1 | func GetStructUnExportedField(source interface{}, fieldName string) (accessableField, addressableSourceCopy reflect.Value) { |
This copies the struct, then uses NewAt on the copy’s field storage.
Mutating without a pointer to the original
Reads work; writes on the copy do not update the caller’s struct — you are editing the duplicate.
Same Set helpers as above; prefer passing a pointer and NewAt when you need in-place updates.
Sample code: NewbMiao/Dig101-Go.
Questions? Leave a comment below or email: newbvirgil@gmail.com![]()
