Created
November 25, 2022 09:46
-
-
Save debedb/2d8d6bee7b2083ea94835ad9c93e2a9b to your computer and use it in GitHub Desktop.
Go: Pointer receivers
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
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