Created
August 19, 2018 18:59
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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