maps: use explicit map value cloning in maps.merge_in_place and maps.merge (fx #22564) (#22576)

This commit is contained in:
Felipe Pena 2024-10-19 05:49:41 -03:00 committed by GitHub
parent 380500a76b
commit 136bdfe93f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 46 additions and 2 deletions

View file

@ -75,8 +75,12 @@ pub fn from_array[T](array []T) map[int]T {
// Note that this function modifes `m1`, while `m2` will not be. // Note that this function modifes `m1`, while `m2` will not be.
pub fn merge_in_place[K, V](mut m1 map[K]V, m2 map[K]V) { pub fn merge_in_place[K, V](mut m1 map[K]V, m2 map[K]V) {
for k, v in m2 { for k, v in m2 {
$if v is $map {
m1[k] = v.clone()
} $else {
m1[k] = v m1[k] = v
} }
}
} }
// merge produces a map, that is the result of merging the first map `m1`, // merge produces a map, that is the result of merging the first map `m1`,
@ -86,7 +90,11 @@ pub fn merge_in_place[K, V](mut m1 map[K]V, m2 map[K]V) {
pub fn merge[K, V](m1 map[K]V, m2 map[K]V) map[K]V { pub fn merge[K, V](m1 map[K]V, m2 map[K]V) map[K]V {
mut res := m1.clone() mut res := m1.clone()
for k, v in m2 { for k, v in m2 {
$if v is $map {
res[k] = v.clone()
} $else {
res[k] = v res[k] = v
} }
}
return res return res
} }

View file

@ -0,0 +1,36 @@
import maps
fn test_main() {
// mmm map declaration as mutable
mut mmm := map[string]map[string]int{}
// adding values to the map mmm
mmm['greet'] = {
'hello': 0
}
mmm['place'] = {
'world': 1
}
mmm['color']['orange'] = 2
// printing the map mmm
assert mmm.str() == "{'greet': {'hello': 0}, 'place': {'world': 1}, 'color': {'orange': 2}}"
// mmm2 map declaration as const
mmm2 := {
'name': {
'Diego': 3
}
}
// printing the map mmm2
assert mmm2.str() == "{'name': {'Diego': 3}}"
// Using the maps module functions
// use of maps.merge is commented but its behavior is the same as merge_in_place
// mmm = maps.merge(mmm, mmm2)
maps.merge_in_place(mut mmm, mmm2)
// printing again mmm to the standard output
assert mmm.str() == "{'greet': {'hello': 0}, 'place': {'world': 1}, 'color': {'orange': 2}, 'name': {'Diego': 3}}"
}