What is correct way to copy struct instance with fields in Go?

54 Views Asked by At

Today I discovered that I don't know how to copy instance in Golang.

While I have deepcopy() in Python, or .clone() in Rust.
And when i googled I saw that in go correct way is dereference. So i did that way.

But noticed that despite i define struct field as value, copy still points to same object in memory. And there was some mentions about specific conditions on array and slices, but not on maps(which is implicit type of http.Header). Those cases, apparently always passed by reference?

So my question is as in title: What is correct way to the deep copy of struct instance in go?

package main

import (
    "fmt"
    "net/http"
)

type (
    Client struct {
        headers http.Header
    }
)

func NewClient() *Client {
    return &Client{headers: make(http.Header)}
}

func (c *Client) Copy() *Client {
    newClient := *c
    newClient.headers.Add("Header", "ValueOne")
    return &newClient
}
func main() {
    origin := NewClient()
    copyOne := origin.Copy()
    fmt.Printf("originAddr: %p\t copyOneAddr: %p\n", origin, copyOne)
    fmt.Printf("originHeaders: %p\t copyOneHeaders: %p\n", origin.headers, copyOne.headers)
    fmt.Printf("originHeaders: %v\t copyOneHeaders: %v\n", origin.headers, copyOne.headers)
}
originAddr: 0xc000014040         copyOneAddr: 0xc000014048
originHeaders: 0xc000028c00      copyOneHeaders: 0xc000028c00
originHeaders: map[Header:[ValueOne]]    copyOneHeaders: map[Header:[ValueOne]]
0

There are 0 best solutions below