"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How do pointers affect value modification in Go functions?

How do pointers affect value modification in Go functions?

Published on 2024-11-07
Browse:124

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:

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}
}

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:

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}
}

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:

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
}

By using p.Value, we modify the original struct's Value field, resulting in an output of 4.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3