您似乎了解 Go 切片。
Go 切片被实现为 struct:
type slice struct {
array unsafe.Pointer
len int
cap int
}
它是底层数组的视图。
例如,
package main
import "fmt"
func main() {
s := []int{2, 3, 5, 7, 11, 13}
fmt.Println("s", cap(s), len(s), s)
t := s[cap(s):]
fmt.Println("s", cap(s), len(s), s)
fmt.Println("t", cap(t), len(t), t)
t = s
fmt.Println("s", cap(s), len(s), s)
fmt.Println("t", cap(t), len(t), t)
}
游乐场:https://play.golang.org/p/i-gufiJB-sP
输出:
s 6 6 [2 3 5 7 11 13]
s 6 6 [2 3 5 7 11 13]
t 0 0 []
s 6 6 [2 3 5 7 11 13]
t 6 6 [2 3 5 7 11 13]
在没有对底层数组任何元素的引用(指针)之前,不会对底层数组进行垃圾回收。
例如,
package main
import "fmt"
func main() {
s := []int{2, 3, 5, 7, 11, 13}
fmt.Println("s", cap(s), len(s), s, &s[0])
t := s
// the slice s struct can be garbage collected
// the slice s underlying array can not be garbage collected
fmt.Println("t", cap(t), len(t), s, &t[0])
p := &t[0]
// the slice t struct can be garbage collected
// the slice t (slice s) underlying array can not be garbage collected
fmt.Println("p", p, *p)
// the pointer p can be garbage collected
// the slice t (and s) underlying array can be garbage collected
}
游乐场:https://play.golang.org/p/PcB_IS7S3QE
输出:
s 6 6 [2 3 5 7 11 13] 0x10458000
t 6 6 [2 3 5 7 11 13] 0x10458000
p 0x10458000 2
阅读:
The Go Blog: Go Slices: usage and internals
The Go Blog: Arrays, slices (and strings): The mechanics of 'append'
The Go Programming Language Specification : Slice types 和 Slice expressions