Does dereferencing a struct return a new copy of struct?

后端 未结 3 1703
-上瘾入骨i
-上瘾入骨i 2020-12-29 07:50

Why when we reference struct using (*structObj) does Go seem to return a new copy of structObj rather than return the same address of original

相关标签:
3条回答
  • 2020-12-29 08:35

    tl;dr Dereferencing (using the * operator) in Go does not make a copy. It returns the value the pointer points to.

    0 讨论(0)
  • 2020-12-29 08:43

    No, "assignment" always creates a copy in Go, including assignment to function and method arguments. The statement obj := *p copies the value of *p to obj.

    If you change the statement p.color = "purple" to (*p).color = "purple" you will get the same output, because dereferencing p itself does not create a copy.

    0 讨论(0)
  • 2020-12-29 08:53

    When you write

    obj := *p
    

    You are copying the value of struct pointed to by p (* dereferences p). It is similar to:

    var obj me = *p
    

    So obj is a new variable of type me, being initialized to the value of *p. This causes obj to have a different memory address.

    Note that obj if of type me, while p is of type *me. But they are separate values. Changing a value of a field of obj will not affect the value of that field in p (unless the me struct has a reference type in it as a field, i.e. slice, map or channels. See here and here.). If you want to bring about that effect, use:

    obj := p
    // equivalent to: var obj *me = p
    

    Now obj points to the same object as p. They still have different addresses themselves, but hold within them the same address of the actual me object.

    0 讨论(0)
提交回复
热议问题