Home > Backend Development > Golang > How Do You Modify the Value Dereferenced by a Pointer in Go?

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

Patricia Arquette
Release: 2024-10-29 08:01:30
Original
297 people have browsed it

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:

<code class="go">func f(p *Test) {
   p = &Test{4}
}</code>
Copy after login

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:

<code class="go">func f(p *Test) {
   *p = Test{4}
}</code>
Copy after login

Implicit Dereferencing:

<code class="go">func f(p *Test) {
   p.Value = 4
}</code>
Copy after login

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.

<code class="go">func f(p **Test) {
   *p = &Test{4}
}</code>
Copy after login

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.

The above is the detailed content of How Do You Modify the Value Dereferenced by a Pointer in Go?. 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