Created
October 21, 2022 06:46
-
-
Save mrk21/ee30465b9dc14da16cca5ba61c8b533a to your computer and use it in GitHub Desktop.
Simple deep copy for Go(reflection/generics)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"reflect" | |
) | |
// Example: | |
// | |
// dest, err := genutil.DeepCopy(src) | |
func DeepCopy(src interface{}) (interface{}, error) { | |
val := reflect.ValueOf(src).Elem() | |
dest := reflect.New(val.Type()).Interface() | |
dumped, err := json.Marshal(src) | |
if err != nil { | |
return nil, err | |
} | |
err = json.Unmarshal(dumped, dest) | |
if err != nil { | |
return nil, err | |
} | |
return dest, nil | |
} | |
// Example: | |
// | |
// dest, err := genutil.DeepCopyGenerics(src) | |
func DeepCopyGenerics[T any](src *T) (*T, error) { | |
dest := new(T) | |
dumped, err := json.Marshal(src) | |
if err != nil { | |
return nil, err | |
} | |
err = json.Unmarshal(dumped, dest) | |
if err != nil { | |
return nil, err | |
} | |
return dest, nil | |
} | |
type Hoge struct { | |
Value1 string | |
} | |
func main() { | |
src := &Hoge{Value1: "value 1"} | |
dest1, err := DeepCopy(src) | |
if err != nil { | |
panic(err) | |
} | |
dest2, err := DeepCopyGenerics(src) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Printf("src: %#v\n", src) | |
fmt.Printf("DeepCopy: %#v\n", dest1) | |
fmt.Printf("DeepCopyGenerics: %#v\n", dest2) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment