可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
Why does a
remain the same? Does append()
generate a new slice?
package main
import (
"fmt"
)
var a = make([]int, 7, 8)
func Test(slice []int) {
slice = append(slice, 100)
fmt.Println(slice)
}
func main() {
for i := 0; i < 7; i++ {
a[i] = i
}
Test(a)
fmt.Println(a)
}
回答1:
In your example the slice
argument of the Test
function receives a copy of the variable a
in the caller's scope.
Since a slice variable holds a "slice descriptor" which merely references an underlying array, in your Test
function you modify the slice descriptor held in the slice
variable several times in a row, but this does not affect the caller and its a
variable.
Inside the Test
function, the first append
reallocates the backing array under the slice
variable, copies its original contents over, appends 100
to it, and that's what you're observing. Upon exiting from Test
, the slice
variable goes out of scope and so does the (new) underlying array that slice references.
If you want to make Test
behave like append
, you have to return the new slice from it — just like append
does — and require the callers of Test
to use it in the same way they would use append
:
func Test(slice []int) []int {
slice = append(slice, 100)
fmt.Println(slice)
return slice
}
a = Test(a)
Please read this article thoroughly as it basically shows you how to implement append
by hand, after explaining how slices are working internally. Then read this.
回答2:
Typical append
usage is
a = append(a, x)
because append
may either modify its argument in-place or return a copy of its argument with an additional entry, depending on the size and capacity of its input. Using a slice that was previously appended to may give unexpected results, e.g.
a := []int{1,2,3}
a = append(a, 4)
fmt.Println(a)
append(a[:3], 5)
fmt.Println(a)
may print
[1 2 3 4]
[1 2 3 5]
回答3:
NOTICE that append generates a new slice if cap is not sufficient. @kostix's answer is correct, or you can pass slice argument by pointer!
回答4:
Try this, which I think makes it clear. the underlying array is changed but our slice is not, print
just prints len()
chars, by another slice to the cap()
, you can see the changed array:
func main() {
for i := 0; i < 7; i++ {
a[i] = i
}
Test(a)
fmt.Println(a) // prints [0..6]
fmt.Println(a[:cap(a)] // prints [0..6,100]
}
回答5:
Go takes a more lean and lazy approach in doing this. It keeps
modifying the same underlying array until the capacity of a slice is
reached.
Ref: http://criticalindirection.com/2016/02/17/slice-with-a-pinch-of-salt/
Output of the example from the link explains the behavior of slices in Go.
Creating slice a.
Slice a len=7 cap=7 [0 0 0 0 0 0 0]
Slice b refers to the 2, 3, 4 indices in slice a. Hence, the capacity is 5 (= 7-2).
b := a[2:5]
Slice b len=3 cap=5 [0 0 0]
Modifying slice b, also modifies a, since they are pointing to the same underlying array.
b[0] = 9
Slice a len=7 cap=7 [0 0 9 0 0 0 0]
Slice b len=3 cap=5 [9 0 0]
Appending 1 to slice b. Overwrites a.
Slice a len=7 cap=7 [0 0 9 0 0 1 0]
Slice b len=4 cap=5 [9 0 0 1]
Appending 2 to slice b. Overwrites a.
Slice a len=7 cap=7 [0 0 9 0 0 1 2]
Slice b len=5 cap=5 [9 0 0 1 2]
Appending 3 to slice b. Here, a new copy is made as the capacity is overloaded.
Slice a len=7 cap=7 [0 0 9 0 0 1 2]
Slice b len=6 cap=12 [9 0 0 1 2 3]
Verifying slices a and b point to different underlying arrays after the capacity-overload in the previous step.
b[1] = 8
Slice a len=7 cap=7 [0 0 9 0 0 1 2]
Slice b len=6 cap=12 [9 8 0 1 2 3]
回答6:
In order to make your code work without having to return the slice from Test, you can pass a pointer like this:
package main
import (
"fmt"
)
var a = make([]int, 7, 8)
func Test(slice *[]int) {
*slice = append(*slice, 100)
fmt.Println(*slice)
}
func main() {
for i := 0; i < 7; i++ {
a[i] = i
}
Test(&a)
fmt.Println(a)
}
回答7:
I think the original answer is not exactly correct. append()
changed both the slices and the underlying array even though the underlying array is changed but still shared by both of the slices.
As specified by the Go Doc:
A slice does not store any data, it just describes a section of an underlying array. (Link)
Slices are just wrapper values around arrays, meaning that they contain information about how they slice an underlying array which they use to store a set of data. Therefore, by default, a slice, when passed to another method, is actually passed by value, instead of reference/pointer even though they will still be using the same underlying array. Normally, arrays are also passed by value too, so I assume a slice points at an underlying array instead of store it as a value. Regarding your question, when you run passed your slice to the following function:
func Test(slice []int) {
slice = append(slice, 100)
fmt.Println(slice)
}
you actually passed a copy of your slice along with a pointer to the same underlying array.That means, the changes you did to the slice
didn't affect the one in the main
function. It is the slice itself which stores the information regarding how much of an array it slices and exposes to the public. Therefore, when you ran append(slice, 1000)
, while expanding the underlying array, you also changed slicing information of slice
too, which was kept private in your Test()
function.
However, if you have changed your code as follows, it might have worked:
func main() {
for i := 0; i < 7; i++ {
a[i] = i
}
Test(a)
fmt.Println(a[:cap(a)])
}
The reason is that you expanded a
by saying a[:cap(a)]
over its changed underlying array, changed by Test()
function. As specified here:
You can extend a slice's length by re-slicing it, provided it has sufficient capacity. (Link)
回答8:
package main
import (
"fmt"
)
func a() {
x := []int{}
x = append(x, 0)
x = append(x, 1) // commonTags := labelsToTags(app.Labels)
y := append(x, 2) // Tags: append(commonTags, labelsToTags(d.Labels)...)
z := append(x, 3) // Tags: append(commonTags, labelsToTags(d.Labels)...)
fmt.Println(y, z)
}
func b() {
x := []int{}
x = append(x, 0)
x = append(x, 1)
x = append(x, 2) // commonTags := labelsToTags(app.Labels)
y := append(x, 3) // Tags: append(commonTags, labelsToTags(d.Labels)...)
z := append(x, 4) // Tags: append(commonTags, labelsToTags(d.Labels)...)
fmt.Println(y, z)
}
func main() {
a()
b()
}
First guess could be
[0, 1, 2] [0, 1, 3]
[0, 1, 2, 3] [0, 1, 2, 4]
but in fact it results in
[0, 1, 2] [0, 1, 3]
[0, 1, 2, 4] [0, 1, 2, 4]
More details see https://allegro.tech/2017/07/golang-slices-gotcha.html
回答9:
Here is a nice implementation of append for slices. I guess its similar to what is going on under the hood:
package main
import "fmt"
func main() {
slice1 := []int{0, 1, 2, 3, 4}
slice2 := []int{55, 66, 77}
fmt.Println(slice1)
slice1 = Append(slice1, slice2...) // The '...' is essential!
fmt.Println(slice1)
}
// Append ...
func Append(slice []int, items ...int) []int {
for _, item := range items {
slice = Extend(slice, item)
}
return slice
}
// Extend ...
func Extend(slice []int, element int) []int {
n := len(slice)
if n == cap(slice) {
// Slice is full; must grow.
// We double its size and add 1, so if the size is zero we still grow.
newSlice := make([]int, len(slice), 2*len(slice)+1)
copy(newSlice, slice)
slice = newSlice
}
slice = slice[0 : n+1]
slice[n] = element
return slice
}