Skip to content

Instantly share code, notes, and snippets.

@debedb
Created November 25, 2022 09:46
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 debedb/2d8d6bee7b2083ea94835ad9c93e2a9b to your computer and use it in GitHub Desktop.
Save debedb/2d8d6bee7b2083ea94835ad9c93e2a9b to your computer and use it in GitHub Desktop.
Go: Pointer receivers
package main
import "fmt"
type _struct struct {
field string
}
func (s *_struct) doStuff(msg string) {
s.field = msg
fmt.Println("I am doing stuff dammit, and field is ", s.field)
}
func (s _struct) doOtherStuff(msg string) {
s.field = msg
// Yeah, man, but this is just your copy.
fmt.Println("I am doing other stuff dammit, and field is ", s.field)
}
type _ifc interface {
doStuff(msg string)
doOtherStuff(msg string)
}
func main() {
var struct1 _struct
fmt.Println("Empty: ", struct1.field)
// See https://stackoverflow.com/questions/42477951/what-is-the-method-set-of-sync-waitgroup
// Automatically will call method with pointer receiver with &struct1:
struct1.doStuff("left")
fmt.Println(struct1.field)
struct1.doOtherStuff("right")
// Still "left" because not a pointer receiver
fmt.Println(struct1.field)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment