I know the value is not same so I double qouted it, what I want to know is how go's map hash works so that cusKey
and a
is different in type result in the key is different.
package main
import (
"fmt"
)
type key int
const cusKey key = 1
const a int = 1
func main() {
dic := make(map[interface{}]interface{})
dic[cusKey] = 5
dic[a] = 6
fmt.Println(dic[cusKey])
fmt.Println(dic[a])
}
the output is
5
6
How go achieve this? The two keys value are all 1
.
I know in go if the type is different, two value is different. So the two 1
is not identical.
But how actually go's map did it? I tried to find out at map.go
in source, but I can't found where go implement the hash funcion. Is it calculates hash of the keys with type annotations?
a
and cusKey
cannot be equal because they have different types. a
is of type int
, and cusKey
is of type key
(which has int
as its underlying type, but it is a different type).
Go maps require keys to be comparable. Spec: Map types:
The comparison operators
==
and!=
must be fully defined for operands of the key type
The key type of your dic
map is interface{}
, it's an interface type, and interface values are comparable if Spec: Comparison operators:
- Interface values are comparable. Two interface values are equal if they have identical dynamic types and equal dynamic values or if both have value
nil
.
An interface value stores the dynamic type and value, schematically, it's a "(value, type)" pair. When interface values are compared, the type is compared too, and if they don't match, the interface value comparison will yield false
. For details about interface representation, see Go Data Structures: Interfaces (by Russ Cox).
For internals about Go's map, check out Dave Cheney: How the Go runtime implements maps efficiently (without generics).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With