Understanding Value Modification with Pointers in Go
In Go, pointers allow for indirect access and modification of values. However, understanding how pointers work is crucial when passing them to functions.
When passing a pointer to a function, two scenarios arise: value modification vs. pointer reassignment.
Scenario 1: Value Modification
Consider this code:
<code class="go">type Test struct { Value int } func main() { var i Test = Test {2} var p *Test = &i f(p) println(i.Value) // 4 } func f(p *Test) { *p = Test{4} }</code>
Here, function f receives a pointer to the Test struct. Inside f, the dereferenced pointer (*p) is assigned a new Test struct with a value of 4. This effectively modifies the original i struct in the main function, and the output is 4.
Scenario 2: Pointer Reassignment
Now, let's change the code slightly:
<code class="go">type Test struct { Value int } func main() { var i Test = Test {2} var p *Test = &i f(p) println(i.Value) // 2 } func f(p *Test) { // ? p = &Test{4} }</code>
In this case, instead of modifying the pointed value, the function reassigns the p pointer to a new Test struct with a value of 4. Since p is a local variable within f, this change does not affect the original i struct in the main function, and the output remains 2.
Solution: Modifying Pointed Value
To modify the pointed value, we must dereference the pointer and directly access the struct member:
<code class="go">type Test struct { Value int } func main() { var i Test = Test {2} var p *Test = &i f(p) println(i.Value) // 4 } func f(p *Test) { p.Value = 4 }</code>
By using p.Value, we modify the original struct's Value field, resulting in an output of 4.
The above is the detailed content of How do pointers affect value modification in Go functions?. For more information, please follow other related articles on the PHP Chinese website!