type slice struct {
array unsafe.Pointer
len int
cap int
}
以下是一些示例:
package main
import "fmt"
func foo(a []int) {
// new array allocated, returned new slice struct
// and it is assigned to local copy of slice struct
a = append(a, 7)
// element changed in local copy of slice struct
a[1] = 7
}
func bar(a *[]int) {
// new array allocated, returned new slice struct
// and it is assigned to the variable declared on first line of main function
// as it is passed by reference
*a = append(*a, 7)
}
func main() {
// new slice, len and capacity equals number of elements
a := []int{1, 2, 3, 4, 5, 6}
fmt.Printf("a[1]=%d\n", a[1])
// array shared, will print a[1]=10
b := a[1:3]
b[0] = 10
fmt.Printf("1. a[1]=%d\n", a[1])
// new array allocated, will print a[1]=10
b = append(b, a...)
b[0] = 100
fmt.Printf("2. a[1]=%d\n", a[1])
// new array allocated, will print a[1]=10
foo(a)
fmt.Printf("3. a[1]=%d\n", a[1])
// will print [1 10 3 4 5 6 7]
bar(&a)
fmt.Printf("4. a=%v\n", a)
}
Append 返回新的切片结构,但底层数组可以共享也可以不共享,具体取决于容量:如果容量足够则共享,否则不共享。
Slice 结构体具有长度、容量和指向底层数组字段的指针:
以下是一些示例:
你是对的,
names1
使用与 相同的底层数组names
。不,输出不应该相同,因为
names
长度为 4,而names1
长度为 5。请注意,两者都有容量 (10)。这是一个例子,可能会稍微澄清这一点: