在Go语言中,分配和直接分配切片、通道和映射的区别是什么?

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

what is difference that make assignment and direct assignment of slice,channel and map in GO language

问题

我是你的中文翻译助手,以下是代码部分的翻译:

a := make(map[string]string, 10)
a["name"] = "Blob"
// 或者
b := map[string]string{}
b["name"] = "Blob"

问题:

  1. "make" 函数是否在堆上分配内存?
  2. "make" 函数是否只是初始化操作中的一个步骤?类似于 C 语言中的 malloc 和 memset 的组合?

请注意,我只提供翻译服务,不回答关于翻译内容的问题。

英文:

I'm new to go language, look this code section

a := make(map[string]string, 10)
a["name"] = "Blob"
// or
b := map[string]string{}
b["name"] = "Blob"

> Questions:
>> Does "make" allocate memory on heap?

>> Does the "make" function only add one step to the initialization operation? like combination of malloc and memset in C language?

答案1

得分: 4

区别在于make(map[string]string, 10)为映射提供了容量提示,而复合字面量map[string]string{}则没有。

在两种情况下,映射都在堆上分配。

make函数和复合字面量都会分配和初始化一个对象。

英文:

The difference is that make(map[string]string, 10) provides a capacity hint for the map and the composite literal map[string]string{} does not.

The maps are allocated on the heap in both cases.

The make function allocates and initializes an object as does the composite literal.

huangapple
  • 本文由 发表于 2017年4月29日 12:28:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/43691791.html
匿名

发表评论

匿名网友

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

确定