以下のドキュメントで説明されていますが、slice の実体は構造体で、実際のデータ(array)へのポインタを保持しています。
Go Slices: usage and internals - The Go Programming Language
Slice internals
A slice is a descriptor of an array segment. It consists of a pointer to the array, the length of the segment, and its capacity (the maximum length of the segment).
:
Slicing does not copy the slice's data. It creates a new slice value that points to the original array . This makes slice operations as efficient as manipulating array indices. Therefore, modifying the elements (not the slice itself) of a re-slice modifies the elements of the original slice
(3) の s = s[:0]
を実行した後で、インデックスではなく slicing によって (2) の時点での slice データを参照することができます。
golang
1 // (2)
2 fmt.Printf("%p %p %p %p %p %p %p\n", s, &s[0], &s[1], &s[2], &s[3], &s[4], &s[5])
3 s = s[2:6]
4 fmt.Printf("%p %p %p %p %p\n", s, &s[0], &s[1], &s[2], &s[3])
5 printSlice(s) // (2)出力 => len=4 cap=4 [5 7 11 13]
6 // (1)の index 2 ~ index 5までスライス
7
8 // (3)
9 fmt.Printf("%p\n", s)
10 s = s[:0]
11 // fmt.Printf("%d\n", s[0]) // panic: runtime error: index out of range [0] with length 0
12 fmt.Printf("%p %p %p %p %p\n", s, s[0:1], s[1:2], s[2:3], s[3:4])
13 fmt.Printf("%d %d %d %d %d\n", s, s[0:1], s[1:2], s[2:3], s[3:4])
14 printSlice(s) // (3)出力 => len=0 cap=4 []
15 // (2) の 〜index0までスライス(empty slice)
16
17 // (4)
18 fmt.Printf("%p %p %p\n", s[1:2], s[2:3], s[3:4])
19 s = s[1:4]
20 fmt.Printf("%p %p %p\n", &s[0], &s[1], &s[2])
21 printSlice(s) // (4)出力 => len=3 cap=3 [7 11 13]
22 // index 1 ~ index 3 までスライス
23 // (3) の[]からスライスするのではなく、
24 // (1) の[2 3 5 7 11 13] からスライスするのでもなく、
25 // (2) の[5 7 11 13]からスライスされる
26
27 // (2)
28 // 0xc00001c120 0xc00001c120 0xc00001c128 0xc00001c130 0xc00001c138 0xc00001c140 0xc00001c148
29 // 0xc00001c130 0xc00001c130 0xc00001c138 0xc00001c140 0xc00001c148
30 // len=4 cap=4 [5 7 11 13]
31 // (3)
32 // 0xc00001c130
33 // 0xc00001c130 0xc00001c130 0xc00001c138 0xc00001c140 0xc00001c148
34 // [] [5] [7] [11] [13]
35 // len=0 cap=4 []
36 // (4)
37 // 0xc00001c138 0xc00001c140 0xc00001c148
38 // 0xc00001c138 0xc00001c140 0xc00001c148
39 // len=3 cap=3 [7 11 13]
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。