Skip to content

Instantly share code, notes, and snippets.

@lechuhuuha
Created August 23, 2025 14:59
Show Gist options
  • Save lechuhuuha/301941a6576f84d52d7052e661777830 to your computer and use it in GitHub Desktop.
Save lechuhuuha/301941a6576f84d52d7052e661777830 to your computer and use it in GitHub Desktop.
value-receive and pointer-receive method
package main
import "fmt"
type Counter struct{ n int }
// ---------------------
// ⬇ value-receiver method
// ---------------------
func (c Counter) Value() int { return c.n }
// ---------------------
// ⬇ pointer-receiver method
// ---------------------
func (c *Counter) Inc() { c.n++ }
func main() {
// ————————————
// 1) Call pointer-receiver on a VALUE
// The compiler silently takes &v so Inc’s *Counter receiver is satisfied.
// ————————————
var v Counter // value
v.Inc() // behind the scenes: (&v).Inc()
fmt.Println(v.Value()) // 1
// ————————————
// 2) Call value-receiver on a POINTER
// The compiler makes a copy of *p and passes that copy to Value().
// ————————————
p := &Counter{3} // pointer
fmt.Println(p.Value()) // compiler does: (*p).Value() → 3
p.Inc()
fmt.Println(p.Value()) // 4
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment