Sobes.tech
Middle+

What will the code with pointers output? How to fix the changePointer function without changing its signature?

sobes.tech AI

Answer from AI

It is difficult to say exactly what the program will output without specific code, but often pointer issues in Go are related to the function receiving a copy of the pointer and modifying it, rather than the actual object or pointer in the calling code.

If a function has the signature func changePointer(p *Type), then inside it, you cannot change the pointer p itself to point to another object, because p is a copy of the pointer.

To fix the function without changing its signature, you should modify the data at the address p points to, not the pointer itself. For example:

func changePointer(p *int) {
    *p = 42 // change the value at the address `p` points to
}

If you need to change the pointer itself, the signature should be func changePointer(p **Type), but this is not allowed to change according to the condition.

In summary: modify the contents at the pointer, not the pointer itself.