Home > Backend Development > Golang > Does Go\'s Dereference Operator Create a Copy or a Reference to the Original Struct?

Does Go\'s Dereference Operator Create a Copy or a Reference to the Original Struct?

Barbara Streisand
Release: 2024-11-28 12:29:10
Original
222 people have browsed it

Does Go's Dereference Operator Create a Copy or a Reference to the Original Struct?

Go Dereferencing: Copies or Not, That Is the Question

When accessing a Go struct using the dereference operator (*), users may wonder if the result is a new copy of the struct or a reference to the original object.

Understanding the Behavior

In the provided code snippet:

type me struct {
    color string
    total int
}

func study() *me {
    p := me{}
    return &p
}

obj := *study()
Copy after login

study() returns a pointer to a me struct. Dereferencing it in obj creates a copy of the struct. This is evident from the memory addresses of &p.color and &obj.color, which are different.

One might expect the dereferenced struct obj to have the same memory address as the original struct, but that's not the case in this instance. This behavior can be attributed to Go's automatic deallocation of variables at the end of their scope.

When It's Actually a Reference

To achieve reference behavior, one can assign a pointer directly to the struct using:

obj := study()
Copy after login

In this case, obj will be a pointer to the original me struct, and changes to either p or obj will affect the same underlying struct.

Conclusion

When dereferencing a struct in Go, it's important to understand that the result is a copy of the original struct unless a pointer to the struct is explicitly assigned. This behavior ensures that changes made to the dereferenced struct do not affect the original struct, maintaining encapsulation and variable independence.

The above is the detailed content of Does Go\'s Dereference Operator Create a Copy or a Reference to the Original Struct?. 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