在golang内部如何进行映射? [重复]

This question already has an answer here:

Here is specific example

func main(){    
m := make(map[string]int)  
m["k1"] = 7  

_, prs := m["k2"]   
fmt.Println(prs)  
}

What does "_" signifies here?
Rest is clear to me.

</div>

See dokumentation. Your statement:

_, prs := m["k2"]

is doing two things at the same time. A) Checking whether a key/value is present in the map and B) is retrieves the value. "prs" is a boolean indicating whether the value was present for the key "k2" or not.

Thus, if you only want to check if a key/value is present in the map and do not care to use the value, you can use the "_" to ignore the value and only use the "prs" boolean.

The _ means that you don't care about this particular return value.

Accessing a map index yield 2 values :

  • The value a that index, or the zero-value of the value type
  • A boolean indicating whether or not a value was at that index

In your case, prs will be the boolean.

This pattern is often used like this :

if _, found := m[key]; !found {
    // Do something here to handle the fact that there is nothing at the index `key`
}

Map being a special type in Go, the second value is optional, so if you don't care about whether or not there is something in the map you don't have to check for it.