2
1
Fork 0
pr3-ws202526/go/02-next-level/00-methods.go

27 lines
565 B
Go

package main
import "fmt"
type Counter struct {
value int
}
// pointer receiver. The method operates directly on the object c points to
// Use a pointer receiver whenever the object needs to be modified.
func (c *Counter) Increment() {
c.value++
}
// value receiver. The method operates on copy of object c. Use a value
// receiver when the object does not need to be modified in the method.
func (c Counter) String() string {
return fmt.Sprintf("Counter value: %d", c.value)
}
func main() {
c := Counter{}
fmt.Println(c)
c.Increment()
fmt.Println(c)
}