Home > Backend Development > Golang > Does Dereferencing a Go Struct Create a Copy or a Reference?

Does Dereferencing a Go Struct Create a Copy or a Reference?

DDD
Release: 2024-12-13 03:11:12
Original
503 people have browsed it

Does Dereferencing a Go Struct Create a Copy or a Reference?

Dereferencing Structs in Go: Creation of New Copies

When working with structs in Go, it's important to understand the behavior of dereferencing. Dereferencing an object essentially returns a copy of the value it points to. This can be counterintuitive for some programmers coming from other languages, where dereferencing typically returns the object itself.

Consider the following Go code snippet:

package main

import (
    "fmt"
)

type me struct {
    color string
    total int
}

func study() *me {
    p := me{}
    p.color = "tomato"
    fmt.Printf("%p\n", &p.color)
    return &p
}

func main() {
    p := study()
    fmt.Printf("&p.color = %p\n", &p.color)

    obj := *p
    fmt.Printf("&obj.color = %p\n", &obj.color)
    fmt.Printf("obj = %+v\n", obj)

    p.color = "purple"
    fmt.Printf("p.color = %p\n", &p.color)
    fmt.Printf("p = %+v\n", p)
    fmt.Printf("obj  = %+v\n", obj)

    obj2 := *p
    fmt.Printf("obj2 = %+v\n", obj2)
}
Copy after login

In this example, the study() function creates a new me struct and returns a pointer to it. We then assign this pointer to a variable p. When we dereference p and assign it to obj, we create a new copy of the struct. This new copy has a different memory address from the original struct pointed to by p.

This means that changing the fields of obj will not affect the fields of the original struct, and vice versa. To create a reference to the original struct, we would need to assign the pointer from p to obj:

obj := p
Copy after login

In this case, obj and p would point to the same struct and any changes made to one would be reflected in the other.

The above is the detailed content of Does Dereferencing a Go Struct Create a Copy or a Reference?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template