Home >Backend Development >Golang >Go Structs: Value Copy or Reference When Dereferencing a Pointer?

Go Structs: Value Copy or Reference When Dereferencing a Pointer?

DDD
DDDOriginal
2024-11-28 20:54:12132browse

Go Structs:  Value Copy or Reference When Dereferencing a Pointer?

Dereferencing Struct: Understanding Value Copy vs. Reference Assignment

When working with structs in Go, the asterisk operator (*) can be used to dereference a struct pointer, raising questions about whether it returns the same struct value or a new copy. Let's clarify this through an example:

Consider the following code:

type me struct {
    color string
    total int
}

func study() *me {
    p := me{}
    p.color = "tomato"
    return &p
}

In this case, the function study() returns a pointer to a me struct. When we call study() in the main function and assign it to p, we are essentially storing a reference to the original me struct. However, when we dereference p using obj := *p, we are copying the value of the struct pointed to by p. This is equivalent to:

var obj me = *p

As a result, obj becomes a new variable of type me, initialized with the same data as the struct pointed to by p. This means that obj and p have separate memory addresses, even though they contain the same data.

It's important to note that if we make any changes to the obj struct, they will not affect the data pointed to by p, unless the me struct contains reference types (such as slices, maps, or channels). In such cases, changes to these fields will be reflected in both obj and the struct pointed to by p.

However, if we want to assign a reference to the same struct as p, instead of copying its value, we can use straight assignment:

obj := p

In this case, obj will hold a direct reference to the same struct as p, and any changes made to obj will also be visible through p.

The above is the detailed content of Go Structs: Value Copy or Reference When Dereferencing a Pointer?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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