Sobes.tech
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 the Counter struct is created inside the method. Incrementing c.val++ changes the copy, not the original, so the value of val in main remains 1.
  • The IncPtr() method has a pointer receiver (c *Counter), so changes inside the method affect the original object. After calling c.IncPtr(), the value of val increases by 1 and becomes 2.

Thus, initially, 1 is printed, and after calling the method with a pointer, 2 is printed.