Last active
April 18, 2020 08:00
-
-
Save olehcambel/90a0937411d1c69bf77c9d111caa2c41 to your computer and use it in GitHub Desktop.
example of pointer's usage. In general, all methods on a given type should have either value or pointer receivers, but not a mixture of both.
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 { | |
I int | |
} | |
func (c counter) Plus() int { | |
return c.I | |
} | |
func (c *counter) Minus() int { | |
c.I-- | |
return c.I | |
} | |
func plus(c counter) int { | |
return c.I | |
} | |
func minus(c *counter) int { | |
c.I-- | |
return c.I | |
} | |
func main() { | |
c := counter{I: 10} | |
fmt.Println(c.Minus()) | |
fmt.Println(c.Plus()) | |
c2 := &counter{I: 10} | |
fmt.Println(minus(c2)) | |
fmt.Println(plus(*c2)) | |
c3 := counter{I: 10} | |
fmt.Println(minus(&c3)) | |
fmt.Println(plus(c3)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment