何时使用make而不是内联切片初始化器?

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

When to use make vs inline slice initializer?

问题

考虑以下两个代码片段:

// 在声明时直接赋值。
os_list := []string{"Mac OSX", "Linux", "Windows 7"}
fmt.Println(os_list)

// 将值追加到空切片中。
os_list_two := make([]string, 3)
os_list_two = append(os_list_two, "Mac OSX", "Linux", "Windows 7")
fmt.Println(os_list_two)

我们应该在什么情况下使用其中之一?

英文:

Consider the following two snippets of code:

// Declaring the values inline.
os_list := []string{"Mac OSX", "Linux", "Windows 7"}
fmt.Println(os_list)

// Appending them to an empty slice.
os_list_two := make([]string, 3)
os_list_two = append(os_list_two, "Mac OSX", "Linux", "Windows 7")
fmt.Println(os_list_two)

When should we use one or the other?

答案1

得分: 10

make函数将为字符串切片分配和初始化内存。在你的例子中,os_list_two包含三个空字符串,索引为0-2,然后是"Mac OSX"、"Linux"和"Windows 7"。最终你得到的切片有六个元素,而不是你可能期望的三个。

你可以在这里看到示例:
http://play.golang.org/p/Vm92dz8LqF

关于make的更多信息:
http://golang.org/ref/spec#Making_slices_maps_and_channels

关于切片的更多信息:
http://blog.golang.org/go-slices-usage-and-internals

当你事先知道需要多大的切片,或者需要在特定位置索引切片,或者零值对你有用时,可以使用make。如果你只需要一个用于追加元素的切片,可以简单地使用[]string{}进行定义。如果你需要使用特定的值初始化切片,就像你对os_list所做的那样,不使用make也是有意义的。

英文:

make will allocate and initialise memory for the string slice. In your example os_list_two contains three empty strings at indexes 0-2, followed by the items "Mac OSX", "Linux", "Windows 7". In the end you have a slice with six elements, not three as you probably expected.

You can see it illustrated here:
http://play.golang.org/p/Vm92dz8LqF

More on make:
http://golang.org/ref/spec#Making_slices_maps_and_channels

And on slices:
http://blog.golang.org/go-slices-usage-and-internals

Use make when you know beforehand how big a slice you need, or you need to index the slice at specific positions, or if the zero-values are in some way useful to you. If you just need a slice to append items to, you can simply define it using []string{}. It can also make sense not to use make if you need to initialise the slice with specific values, like you did for os_list.

答案2

得分: -2

这两组语句具有完全相同的效果。只有在你有一组要开始的数据时,才需要内联声明值。相反,如果你想以空字符串开始,并在处理数据时逐步添加值(例如解析文件),那么你将使用第二组语句。

英文:

These two sets of statements have the exact same effect. The only reason to declare the values inline is when you have a set of data you want to start with. Conversely, if you want to start with an empty string and append values as you process data (such as parsing a file), then you would use the second set of statements.

huangapple
  • 本文由 发表于 2013年12月10日 05:47:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/20481491.html
匿名

发表评论

匿名网友

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

确定