Created
January 23, 2019 10:19
-
-
Save Petelin/0db02415725606d758d0c4c4a90b74d5 to your computer and use it in GitHub Desktop.
go通过反射替换任意变量的函数
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
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