-3

Golang is a native programming language. So there is a lot of limitation than dynamic languages (like python and ruby).

When initialize Maps as m := make(Map[string]int), this map m seems to be able to contain infinity many key-values.

But when initialize Maps with maps literal or make with cap, The maps cannot contain infinity many key-values.

Some article said that make without cap allocate a huge amount of memory to this map. But this is not option, because if it was true, there will be a giant memory consumption when initialize single map. But no matter what computer hardware monitoring tools I use, the memory is no difference between before and during my program runs.


func main(){
    Hello()
}

func Hello(){
    m := make(SizeRecord)
    l := 10000000
    for i := 0; i < l; i++ {
        m[strconv.Itoa(i)] = Size{float64(rand.Intn(100)), float64(rand.Intn(100)), float64(rand.Intn(100))}
    }

    fmt.Println(m)
}

The program take a while to be executed.

I also read an article Go maps in action, it said (I don't know if I have understood correctly) that make without cap use an alternative implementation to represent map and use an unified interface to access the map as the other maps with limited capacity.

If my understanding is wrong, could any body tell me what correct one is?

If I am correct, why didn't golang implement all maps in this way?

Audra Jacot
  • 139
  • 7

1 Answers1

0

Your understanding of how maps work is incorrect. The spec says:

Blockquote The initial capacity does not bound its size: maps grow to accommodate the number of items stored in them, with the exception of nil maps. A nil map is equivalent to an empty map except that no elements may be added.

So, the capacity is only a hint and it affects the initial size of the map. The map can grow as needed. There is no separate implementation for maps with a given capacity.

Burak Serdar
  • 46,455
  • 3
  • 40
  • 59
  • But why it will cause panic when set key-value to an empty maps? – Audra Jacot Oct 25 '19 at 04:03
  • 1
    If you set key-value of an empty map, it will not panic. If you set key-value of a nil map, then it will panic. Maps are reference types, you have to initalize them before you use them. Either use `new`, or declare it as an empty map, like `myMap:=map[string]string{}`. This map is non-nil, but empty, and you can use it. If you do `var myMap map[string]string`, then this map is nil, and when you use it, it will panic. – Burak Serdar Oct 25 '19 at 04:06