在golang中,我们可以使用len()函数来判断map是否有值。如果map的长度为0,则表示map没有任何键值对。
另外,在访问map时,可以使用ok-idiom来判断指定的键是否存在于map中。例如:
m := make(map[string]int)
m["a"] = 1
if val, ok := m["a"]; ok {
fmt.Println("a exists in the map and its value is", val)
} else {
fmt.Println("a does not exist in the map")
}
这段代码首先创建了一个空的字符串到整数的映射(即map),然后向其中添加了一个键值对”a”: 1。接着通过ok-idiom判断键”a”是否存在于map中,并输出相应信息。因为”a”存在于map中,所以输出结果为”a exists in the map and its value is 1”。