Skip to content

Instantly share code, notes, and snippets.

@geekman
Created April 10, 2023 10:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save geekman/477c8c37906477068d2a52c5cd85581c to your computer and use it in GitHub Desktop.
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
//
// 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