获取 Go 语言 map 长度的最简单方法是使用 len() 函数,它返回 map 中元素的数量。此外,还可使用 reflect.Value.Len() 函数、遍历 map 计数或使用 make() 函数创建一个指定长度的新 map 来获取 map 长度。

如何获取 Go 语言 map 长度
在 Go 语言中,获取 map 长度的最简单方法是使用 len() 函数。它返回 map 中元素的数量。
myMap := map[string]int{"foo": 1, "bar": 2}
length := len(myMap) // 返回 2以下是一些其他方法可以获取 map 长度:
- 使用
reflect.Value.Len()函数:
import "reflect"
myMap := map[string]int{"foo": 1, "bar": 2}
reflectedMap := reflect.ValueOf(myMap)
length := reflectedMap.Len() // 返回 2- 通过遍历 map 计数:
myMap := map[string]int{"foo": 1, "bar": 2}
length := 0
for range myMap {
length++
} // 返回 2- 使用
make()函数创建一个指定长度的新 map:
myMap := make(map[string]int) myMap["foo"] = 1 myMap["bar"] = 2 length := len(myMap) // 返回 2










