How do pointers affect value modification in Go functions?

Linda Hamilton
Release: 2024-10-27 02:32:02
Original
565 people have browsed it

How do pointers affect value modification in Go functions?

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 = &amp;i
   f(p)
   println(i.Value)  // 4
}
func f(p *Test) {
   *p = Test{4}
}</code>
Copy after login

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 = &amp;i
   f(p)
   println(i.Value)  // 2
}
func f(p *Test) {
   // ?
   p = &amp;Test{4}
}</code>
Copy after login

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 = &amp;i
   f(p)
   println(i.Value)  // 4
}
func f(p *Test) {
   p.Value = 4
}</code>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!