Created
          August 23, 2025 14:59 
        
      - 
      
- 
        Save lechuhuuha/301941a6576f84d52d7052e661777830 to your computer and use it in GitHub Desktop. 
    value-receive and pointer-receive method
  
        
  
    
      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 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