Skip to content

Instantly share code, notes, and snippets.

@NaniteFactory
Created August 19, 2018 18:59
Show Gist options
  • Select an option

  • Save NaniteFactory/56f3717c131328563862db79529effee to your computer and use it in GitHub Desktop.

Select an option

Save NaniteFactory/56f3717c131328563862db79529effee to your computer and use it in GitHub Desktop.
A hacky way to access an unexported field (a private member) of a struct from an external package.
// Hack an unexported (private) member of a struct.
// ptrToTargetStruct - a ptr to that struct.
// member - name of an unexported field.
func Hack(ptrToTargetStruct interface{}, member string) *TYPE_MEMBER {
return *(**TYPE_MEMBER)(unsafe.Pointer(reflect.Indirect(reflect.ValueOf(ptrToTargetStruct)).FieldByName(member).UnsafeAddr()))
}
//
// type TARGET struct {
// privateMemer *TYPE_MEMBER
// }
//
// member := Hack((*TARGET)(arg), "privateMember")
//
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment