Skip to content

Instantly share code, notes, and snippets.

@cjgiridhar
Created February 20, 2019 15:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cjgiridhar/f95a5f6b1890d9a4b9ac0a8343806bdd to your computer and use it in GitHub Desktop.
Save cjgiridhar/f95a5f6b1890d9a4b9ac0a8343806bdd to your computer and use it in GitHub Desktop.
Deep Copy Maps in Golang
package main
import (
"encoding/json"
"errors"
"fmt"
)
func deepCopyMap(src map[string]int, dst map[string]int) error {
if src == nil {
return errors.New("src cannot be nil")
}
if dst == nil {
return errors.New("dst cannot be nil")
}
jsonStr, err := json.Marshal(src)
if err != nil {
return err
}
err = json.Unmarshal(jsonStr, &dst)
if err != nil {
return err
}
return nil
}
func main() {
scores := map[string]int{"Alice": 90, "Bob": 100}
// Returns Scores: map[Alice:90 Bob:100]
fmt.Println("Scores:", scores)
dstScores := make(map[string]int)
deepCopyMap(scores, dstScores)
dstScores["Celine"] = 110
// Returns Scores: map[Alice:90 Bob:100]
fmt.Println("Scores:", scores)
// Returns Dst Scores: map[Alice:90 Bob:100 Celine:110]
fmt.Println("Dst Scores:", dstScores)
}
@wwhtrbbtt
Copy link

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment