Подтвердить что ты не робот

Как подсчитать элементы на карте Go?

Если я хочу подсчитать элементы в структуре карты, какую формулировку я должен использовать? Я попытался использовать

for _, _ := range m {...}

но синтаксис кажется ложным.

4b9b3361

Ответ 1

Используйте len(m). С http://golang.org/ref/spec#Length_and_capacity

len(s)    string type      string length in bytes
          [n]T, *[n]T      array length (== n)
          []T              slice length
          map[K]T          map length (number of defined keys)
          chan T           number of elements queued in channel buffer

Вот пара примеров, портированных из ныне вышедшей из употребления документации SO:

m := map[string]int{}
len(m) // 0

m["foo"] = 1
len(m) // 1

Если переменная указывает на карту nil, то len возвращает 0.

var m map[string]int
len(m) // 0

Excerpted from Maps - Counting map elements. The original author was Simone Carletti. Attribution details can be found on the contributor page. The source is licenced under CC BY-SA 3.0 и may be found in the Documentation archive. Reference topic ID: 732 и example ID: 2528.