Golang deep copy function to copy data from one form of struct to another

Viewed 31

So I'm trying to write a function to deep copy one struct to another. It's not necessary that the two structs be the same. The following is what I have come up with but I'm running into some errors.

package main

import (
    "encoding/json"
    "fmt"
)

type Old struct {
    Name string
}

type New struct {
    Name string
}

func DeepCopy(oldStruct Old, newStruct *interface{}) {
    newJSON, _ := json.Marshal(oldStruct)
    _ = json.Unmarshal(newJSON, &newStruct)
    return
}

func main() {
    old := Old{
        Name: "shreesh",
    }

    new := New{}
    DeepCopy(old, &new)

    fmt.Println(old, new)
}

go playground: https://go.dev/play/p/TXncaPnQSiT

1 Answers

It works using func DeepCopy(oldStruct Old, newStruct *New). But this is probably not how you want to design your code. You're also discarding the error result (which may be fine in this specific scenario).

Also, I think your intention is to use dynamic types for the newStruct parameter which works when not using a pointer: func DeepCopy(oldStruct Old, newStruct interface{}).

Related