golang the map so you can compare

A special distinction map element

If the key exists in the map, then the key corresponding to the obtained value; if the key does not exist, then the obtained value corresponding to zero value type.
What if the element type is a number, you may need to distinguish between an existing 0, 0, and there is no return to zero value it? Very simple, like this:

age, ok := ages["Tom"]
if !ok { /* "Tom"不是一个key,age == 0 */}

Combine better

if age, ok := ages["bob"]; !ok { /* ... */ }
Two, map Compare

And the same slice, can not be compared for equality between Map; only exception is nil and compared. To determine whether the two map contains the same key and value, we must achieve through a cycle:

func equal(x, y map[string]int) bool {
    if len(x) != len(y) {
        return false
    }
    for k, xv := range x {
        if yv, ok := y[k]; !ok || yv != xv {
            return false
        }
    }
    return true
}

Sometimes we need a map is a slice of key type, but the map's key type must be comparable, but the slice does not satisfy this condition. However, we can circumvent this limitation by two steps. The first step, define a helper function k, will slice into the corresponding map type string key, ensure k (x) == k (y) was set up equal only x and y. Then create a string for the key type of map, the map each time the first operation auxiliary function with the k slice is converted to a string type.

The following example demonstrates how to use the map to record the number of submissions of the same list of strings. It uses fmt.Sprintf function to convert character string to a list of key string for the map information is recorded for each element of the string by faithfully% q parameters:

var m = make(map[string]int)

func k(list []string) string { return fmt.Sprintf("%q", list) }

func Add(list []string)       { m[k(list)]++ }
func Count(list []string) int { return m[k(list)] }

Using the same technique can handle any type of non-key comparison, and not just slice type.


What questions please leave a message comments area to explore together!

Released four original articles · won praise 0 · Views 64

Guess you like

Origin blog.csdn.net/forjie_/article/details/103921659