Created
December 1, 2023 06:55
-
-
Save fengxsong/43ae44a63732d426976353d92997e3ee to your computer and use it in GitHub Desktop.
change value of a private field in Go struct
This file contains 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
package main | |
import ( | |
"fmt" | |
"reflect" | |
"unsafe" | |
) | |
type private struct { | |
val string | |
} | |
func (p *private) Val() string { | |
return p.val | |
} | |
type T interface { | |
Val() string | |
} | |
func New() T { | |
return &private{} | |
} | |
func changeVal[V any, P *V](dst any, name string, nval V) { | |
dstRv := reflect.Indirect(reflect.ValueOf(dst)) | |
member := dstRv.FieldByName(name) | |
ptrOfMember := unsafe.Pointer(member.UnsafeAddr()) | |
realPtrToY := (P)(ptrOfMember) | |
*realPtrToY = nval | |
} | |
func main() { | |
t := New() | |
changeVal[string, *string](t, "val", "string") | |
fmt.Println(t.Val()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment