Skip to content

Instantly share code, notes, and snippets.

@debedb
Created November 25, 2022 09:46
Embed
What would you like to do?
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