Senior
func updateV1(px *int) { x2 := 20 px = &x2 } func updateV2(px *int) { *px = 20 } func main() { x := 10 updateV1(&x) fmt.Println(x) updateV2(&x) fmt.Println(x) }
sobes.tech AI
Answer from AI
This code contains two functions that accept a pointer to an int but work differently:
func updateV1(px *int) {
x2 := 20
px = &x2
}
func updateV2(px *int) {
*px = 20
}
func main() {
x := 10
updateV1(&x)
fmt.Println(x) // Will print 10
updateV2(&x)
fmt.Println(x) // Will print 20
}
Explanation:
- In
updateV1, the parameterpxis a local copy of the pointer. Assigningpx = &x2only changes the local copy and does not affect the variablexinmain. - In
updateV2, dereferencing the pointer*px = 20changes the value at the addresspxpoints to. This modifies the value ofxinmain.
Result: updateV1 does not change the original variable, but updateV2 does.
This demonstrates the difference between modifying a local copy of a pointer and changing the value at the address it points to.