初始化一个map有哪些更好的方式?

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

Which is the nicer way to initialize a map?

问题

map 是引用类型。以下是 m := make(map[string]int32)m := map[string]int32{} 之间的区别:

  1. m := make(map[string]int32):这种方式使用了 make 函数来创建一个空的 map,并分配了内存空间。这样做可以确保 map 被正确初始化,并且可以立即开始使用。

  2. m := map[string]int32{}:这种方式使用了字面量语法来创建一个空的 map。在这种情况下,map 不需要使用 make 函数进行显式的初始化,因为字面量语法已经为其提供了初始值。

总的来说,两种方式都可以创建一个空的 map,但使用 make 函数可以提供更多的灵活性,例如可以指定初始容量或者预分配内存空间。而使用字面量语法则更加简洁。

英文:

As map is a reference type. What is difference between:?

m := make(map[string]int32)

and

m := map[string]int32{}

答案1

得分: 269

一个允许你初始化容量,一个允许你初始化值:

// 在重新分配之前,初始化一个具有15个项目空间的映射
m := make(map[string]int32, 15)

// 初始化一个映射,将名称"bob"与数字5相关联
m := map[string]int{"bob": 5}

对于容量为0的空映射,它们是相同的,只是个人偏好。

英文:

One allows you to initialize capacity, one allows you to initialize values:

// Initializes a map with space for 15 items before reallocation
m := make(map[string]int32, 15)

vs

// Initializes a map with an entry relating the name "bob" to the number 5
m := map[string]int{"bob": 5} 

For an empty map with capacity 0, they're the same and it's just preference.

huangapple
  • 本文由 发表于 2015年6月26日 12:03:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/31064688.html
匿名

发表评论

匿名网友

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

确定