Skip to content

Instantly share code, notes, and snippets.

@olehcambel
Last active April 18, 2020 08:00
Show Gist options
  • Save olehcambel/90a0937411d1c69bf77c9d111caa2c41 to your computer and use it in GitHub Desktop.
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.
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