Skip to content

Instantly share code, notes, and snippets.

@iamgoangle
Created September 28, 2019 14:52
Show Gist options
  • Select an option

  • Save iamgoangle/f9ee373498ea662ab6ad5b68ca2d9895 to your computer and use it in GitHub Desktop.

Select an option

Save iamgoangle/f9ee373498ea662ab6ad5b68ca2d9895 to your computer and use it in GitHub Desktop.
Value receiver vs Pointer receiver
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