Created
September 28, 2019 14:52
-
-
Save iamgoangle/f9ee373498ea662ab6ad5b68ca2d9895 to your computer and use it in GitHub Desktop.
Value receiver vs Pointer receiver
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
| package main | |
| import ( | |
| "fmt" | |
| ) | |
| type Count struct { | |
| People int | |
| } | |
| func (c *Count) IncPointer() { | |
| fmt.Printf("address -> %p of `c.People` \n", &c.People) | |
| c.People += 1 | |
| } | |
| func (c Count) Inc() { | |
| fmt.Printf("address -> %p of `c.People` \n", &c.People) | |
| c.People += 1 | |
| } | |
| func main() { | |
| p := &Count{People: 0} | |
| p.IncPointer() | |
| p.IncPointer() | |
| p.IncPointer() | |
| fmt.Println(p.People) | |
| v := Count{People: 0} | |
| v.Inc() | |
| v.Inc() | |
| v.Inc() | |
| fmt.Println(v.People) | |
| } | |
| /* Output | |
| address -> 0x414020 of `c.People` | |
| address -> 0x414020 of `c.People` | |
| address -> 0x414020 of `c.People` | |
| 3 | |
| address -> 0x414028 of `c.People` | |
| address -> 0x41402c of `c.People` | |
| address -> 0x414040 of `c.People` | |
| 0 | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment