map中的key,如何使用对象作为key. 现在项目中都是使用一个string作为key,但有时一个string是不够的,有时需要某个对象中的两个属性来决定map中的key是否相等.像c++中map是需要一个hash函数和equal函数来判断的. Golang中如何处理呢? 比如有一个对象 Person定义如下, 有这样一个map[Person]string,同时使用 person中的name和age决定一个对象是否重复,进行hash等. type Person struct { name string age int sex string }
func printKey3Exists(m *map[int]int, t *testing.T) { if v, ok := (*m)[3]; ok { t.Logf("key 3's value is %d", v) } else { t.Log("key 3 is not existing.") } }
func TestMapVal(t *testing.T) { var m = map[string]int {"one":1,"two":2,"three":3,"four":4,"five":5} for k,v:=range m { t.Log(k,v) } } 运行后输出值为: Map_test.go:25: four 4 Map_test.go:25: five 5 Map_test.go:25: one 1 Map_test.go:25: two 2