Home > Backend Development > Golang > How to determine if a pointer passed as a function argument is being modified, or if the copy is being modified?

How to determine if a pointer passed as a function argument is being modified, or if the copy is being modified?

WBOY
Release: 2024-02-06 10:15:11
forward
1052 people have browsed it

How to determine if a pointer passed as a function argument is being modified, or if the copy is being modified?

Question content

package main

import (
    "fmt"
)

type Numbers struct {
    x int
    y int
}

func initial(number *Numbers) {
    number.x = 1
    number.y = 1
}

func final(number *Numbers) {
    number = &Numbers{2, 2}
}

func main() {
    p := Numbers{0, 0}
    fmt.Println(p) //Prints {0 0}

    initial(&p)
    fmt.Println(p) //Prints {1 1}

    final(&p)
    fmt.Println(p) //Expected to print {2, 2} but prints {1, 1}
}
Copy after login

Why does the initial function modify the pointer, while the final function modifies a copy of the pointer?

The function parameters of

initial and final point to the memory address of p in main; initial p can be changed, final cannot.

Any explanation as to why this is happening would be greatly appreciated.


Correct answer


To modify the data pointed to by a pointer, the pointer must be dereferenced. The dereference operator is *. However, for ease of use, Go implicitly inserts dereference operations in some cases. For example, number.x = 1 is converted to (*number).x = 1.

This implicit translation can be confusing, but you should see that if the translation did not occur, the expression number.x = 1 would be meaningless because number is a pointer type, and pointers have no fields.

To summarize, initial functions have implicit pointer dereferences, while final does not.

If you change final to explicitly and correctly dereference, *number = Numbers{2, 2}, then it will also change p.

The above is the detailed content of How to determine if a pointer passed as a function argument is being modified, or if the copy is being modified?. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template