Skip to content

Instantly share code, notes, and snippets.

@Petelin
Created January 23, 2019 10:19
Show Gist options
  • Save Petelin/0db02415725606d758d0c4c4a90b74d5 to your computer and use it in GitHub Desktop.
Save Petelin/0db02415725606d758d0c4c4a90b74d5 to your computer and use it in GitHub Desktop.
go通过反射替换任意变量的函数
func TestH(t *testing.T) {
say := func() {
fmt.Println("say")
}
rec := patchFunction(&say, func() { fmt.Println("replace") })
say()
rec()
say()
}
func patchFunction(item interface{}, new interface{}) func() {
old := reflect.ValueOf(item).Elem().Interface()
rec := func() {
reflect.ValueOf(item).Elem().Set(reflect.ValueOf(old))
}
reflect.ValueOf(item).Elem().Set(reflect.ValueOf(new))
return rec
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment