Created
February 20, 2019 15:07
-
-
Save cjgiridhar/f95a5f6b1890d9a4b9ac0a8343806bdd to your computer and use it in GitHub Desktop.
Deep Copy Maps in Golang
This file contains hidden or 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" | |
"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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks!