mirror of
https://github.com/vlang/v.git
synced 2025-09-13 14:32:26 +03:00
This commit is contained in:
parent
380500a76b
commit
136bdfe93f
2 changed files with 46 additions and 2 deletions
|
@ -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
|
||||||
}
|
}
|
||||||
|
|
36
vlib/maps/maps_clone_test.v
Normal file
36
vlib/maps/maps_clone_test.v
Normal 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}}"
|
||||||
|
}
|
Loading…
Add table
Add a link
Reference in a new issue