"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 You Modify the Value Dereferenced by a Pointer in Go?

How Do You Modify the Value Dereferenced by a Pointer in Go?

Published on 2024-11-08
Browse:604

How Do You Modify the Value Dereferenced by a Pointer in Go?

Modifying the Value Dereferenced by a Pointer in Go

Passing pointers to functions allows for modifying the values they refer to. However, it requires understanding the inner workings of pointers to perform this operation correctly.

Dereferencing Pointers

To modify a value pointed to by a pointer, it is essential to dereference the pointer. In Go, the asterisk operator (*) is used for this purpose. By dereferencing a pointer, you can access the underlying value it points to.

Changing Pointer Values vs. Pointed Values

The key distinction is between changing the value of a pointer and changing the value it points to. Assigning a new value to a pointer variable only changes the address it stores. For instance, the code snippet below does not modify the value pointed to:

func f(p *Test) {
   p = &Test{4}
}

Modifying Pointed Values

To modify the value pointed to, it is necessary to use the dereferencing operator. This can be done explicitly or implicitly.

Explicit Dereferencing:

func f(p *Test) {
   *p = Test{4}
}

Implicit Dereferencing:

func f(p *Test) {
   p.Value = 4
}

In both cases, the value pointed to by p is changed.

Pointer to Pointer Modification

Passing a pointer to a pointer (*Test) allows for modifying the pointer value stored in the main function. However, it will not change the value pointed to by the original pointer.

func f(p **Test) {
   *p = &Test{4}
}

In summary, when passing pointers to functions, it is crucial to understand the difference between modifying a pointer's value and modifying the value it points to. Dereferencing pointers is essential for performing the latter operation, enabling modifications to the underlying data values.

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