dictionary - Comparing the values of maps in GO -
i have compare values (not keys) of 2 maps of type 'map[string]float64
'.
the contents of maps : map1[abcd:300 pqrs:400]
, map2[abcd:30 pqrs:40]
no check if value(map1)/value(map2) > = 1 (like 300/30=10>1), something.
how can achieve in go ? tia.
i tried :
for key := range m2{ k := range m1{ temp := m1[k] / m2[key] fmt.println("temp*******", temp) } }
breaking down main loop:
for key, value1 := range m1 { if value2, ok := m2[key]; ok { fmt.printf("%f / %f = %f\n", value1, value2, value1/value2) if value2 != 0 && value1/value2 > 1 { fmt.println("greater 1!") } else { fmt.println("not greater 1!") } } }
first use range
pull out both value , key every entry in m1, since need both.
second, using comma ok syntax of value2, ok := m2[key]
, i'm both finding out associated value of second map given key, , ensuring that map entry exists when surrounding if ... ; ok
. description of problem, isn't necessary check every element of second map, share keys first. it's important make check, since go doesn't throw errors when checking map non-existent key, silently returns zero-value of variable--in scenario mean dividing 0 later on.
third, well, formatted printlines see what's happening, real juice simple if value1/value2 > 1
statement. note added in playground link map entries don't fulfill requirement demonstrate behavior correct.
the "go maps in action" blog article linked in other answer indeed great source working maps in go.
Comments
Post a Comment