Back to questions
JuniorTheoryCommon
What does the program print?
package main
import "fmt"
type Counter struct{ n int }
func (c Counter) Inc() int { c.n++; return c.n }
func main() {
var c Counter
fmt.Println(c.Inc(), c.Inc())
}1 1
- Expecting
1 2: a value receiver gets a copy ofcon every call, so each call raises its own copy from0to1andc.nstays0. - Expecting a value receiver to be read-only: the method may change its copy freely, and
return c.nreturns that changed copy's1.
- What does the program print if
Incgets the pointer receiver(c *Counter)? - What is the value of
c.nafter the two calls in this program?