英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论