Intern
What will the code output when executed? package main import "fmt" type Counter struct { val int } func (c Counter) IncVal() { c.val++ } func (c *Counter) IncPtr() { c.val++ } func main() { c := Counter{val: 1} c.IncVal() fmt.Print(c.val, " ") c.IncPtr() fmt.Print(c.val) }
sobes.tech AI
Answer from AI
The code will output:
1 2
Explanation:
- The
IncVal()method has a value receiver (c Counter), so a copy of theCounterstruct is created inside the method. Incrementingc.val++changes the copy, not the original, so the value ofvalinmainremains 1. - The
IncPtr()method has a pointer receiver (c *Counter), so changes inside the method affect the original object. After callingc.IncPtr(), the value ofvalincreases by 1 and becomes 2.
Thus, initially, 1 is printed, and after calling the method with a pointer, 2 is printed.