A Tour of GoでGo言語を学習中、sliceで理解できないところがありました。
「More types: structs, slices, and maps.」の「Slice length and capacity」という項目です。
以下がそのコードです。
package main | |
import "fmt" | |
func main() { | |
s := []int{2, 3, 5, 7, 11, 13} //⑴ | |
printSlice(s) //(1) | |
// Slice the slice to give it zero length. | |
s = s[:0] //⑵ | |
printSlice(s) //⑵ | |
// Extend its length. | |
s = s[:4] //⑶ | |
printSlice(s) //⑶ | |
// Drop its first two values. | |
s = s[2:] //⑷ | |
printSlice(s) //⑷ | |
} | |
func printSlice(s []int) { | |
fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s) | |
} |
で、実行結果がこれ。
len=6 cap=6 [2 3 5 7 11 13] //⑴ len=0 cap=6 [] //⑵ len=4 cap=6 [2 3 5 7] //⑶ len=2 cap=4 [5 7] //⑷
コードの⑴、⑵、⑷は理解できます。
(3)がわかりません。
- (1)変数sを定義し、lengthが6、capacityが6のsliceをsに代入する。sは[2 3 5 7 11 13]。
- (2)sを[:0]でスライスして、sに再代入する。lengthが0、capacityが6になる。sは[]。
- (3)sを[:4]でスライスして、sに再代入する。←疑問: ⑵でsliceのlengthが0になりました。そのsliceを[:4]でスライスして、なぜ実行結果が len=4 cap=6 [2 3 5 7] になるのか?なぜ中身が復活してくるのか?
- (4)sを[2:]でスライスして、sに再代入する。lengthが2、capacityが4になる。sは[5 7]。
(2)のコードがなく、(1)→(3)→(4)の順に実行されていれば理解できるのですが...
謎が判明したら、本記事を更新します!
0 件のコメント:
コメントを投稿