如何在GO语言中增加地图的分配大小?

huangapple go评论83阅读模式
英文:

how do i increase a map's allocation size in GO language?

问题

我有一个对象的集合,有时会添加新的元素。

如何增加内部映射的大小?

当元素数量超过分配的数量时,是否需要重新分配整个映射?

英文:

I have a collection of objects that will sometime have new element added to it.

How do I increase the internal map size?

Do I need to reallocate the whole map every time the element count exceed allocated count?

答案1

得分: 55

根据Go规范:

使用内置函数make创建一个新的空映射值,该函数接受映射类型和可选的容量提示作为参数:

make(map[string]int)
make(map[string]int, 100)

初始容量并不限制其大小:映射会根据存储在其中的项目数量进行自动扩容。

所以,一旦创建了映射,你不需要进行任何分配操作。这由Go运行时内部处理。在创建映射时使用的可选容量只是一个提示,而不是限制。

英文:

The Go specification says:

>A new, empty map value is made using the built-in function make, which takes the map type and an optional capacity hint as arguments:
>
make(map[string]int)
make(map[string]int, 100)
>The initial capacity does not bound its size: maps grow to accommodate the number of items stored in them

So, no, you don't have to make any allocations to a map once you've created it. This is handled internally by the Go runtime. The optional capacity used when making the map it's only a hint, not a limitation.

huangapple
  • 本文由 发表于 2013年6月5日 18:12:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/16937203.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定