Created
April 10, 2023 10:25
-
-
Save geekman/477c8c37906477068d2a52c5cd85581c to your computer and use it in GitHub Desktop.
golang function pointer with object instance (or whatever it's called) https://go.dev/play/p/RsPDtGf_DJe
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
// | |
// does assigning a function pointer carry with it the associated object? | |
// | |
package main | |
import "fmt" | |
// a "function pointer" and its implementation (well, one of it) | |
var FuncPtr func(v string) | |
func a(v string) { | |
fmt.Printf("func a, from %s\n", v) | |
} | |
// some object and a method, matching the FuncPtr signature | |
type Obj int | |
func (o *Obj) Print(s string) { | |
fmt.Printf("Print obj %d, from %s\n", *o, s) | |
} | |
func main() { | |
// assign default impl | |
FuncPtr = a | |
FuncPtr("main") // call it | |
o := Obj(52) | |
FuncPtr = o.Print | |
FuncPtr("main") // call it | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment