<link href='https://www.blogger.com/dyn-css/authorization.css?targetBlogID=1360333113251394764&amp;zx=f14a5390-1aca-4ce7-9a05-978ad86f8197' rel='stylesheet'/>

2018/10/29

Go言語 sliceの謎

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)
}
view raw slice-len-cap.go hosted with ❤ by GitHub

で、実行結果がこれ。

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. (1)変数sを定義し、lengthが6、capacityが6のsliceをsに代入する。sは[2 3 5 7 11 13]。

  2. (2)sを[:0]でスライスして、sに再代入する。lengthが0、capacityが6になる。sは[]。

  3. (3)sを[:4]でスライスして、sに再代入する。←疑問: ⑵でsliceのlengthが0になりました。そのsliceを[:4]でスライスして、なぜ実行結果が len=4 cap=6 [2 3 5 7] になるのか?なぜ中身が復活してくるのか?

  4. (4)sを[2:]でスライスして、sに再代入する。lengthが2、capacityが4になる。sは[5 7]。

(2)のコードがなく、(1)→(3)→(4)の順に実行されていれば理解できるのですが...

謎が判明したら、本記事を更新します!


0 件のコメント:

コメントを投稿

人気の投稿

Original text