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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment