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