モバイルアプリのサーバ側を Go で書いていて、スライスをクリアしたい箇所が出てきました。
Go をちょっと使ってはしばらく使わなくなる間に記憶が抜け落ち、スライスの使い方については公式 Wiki の SliceTricks を毎回参照しますが、なぜかクリアする方法が書かれていないので調べました。
これに近い別ページを以前にブックマークしていたことすら忘れていました…。 もう忘れないように、また、上記ページが消えてしまっても困らないように、自分でここにメモしておきます。
操作による要素数や容量の変化を記しているので、消し方だけでなくスライスの性質自体も掴めると思います。
確認用の出力を行う関数
func showSliceInfo(s []string) { fmt.Printf("len:%d cap:%d %p %v\n", len(s), cap(s), s, s) }
nil を使う方法
s := []string{"one", "two", "three"} showSliceInfo(s) // len:3 cap:3 0xc000060150 [one two three] s = nil // クリア showSliceInfo(s) // len:0 cap:0 0x0 [] s = append(s, "four") showSliceInfo(s) // len:1 cap:1 0xc000010230 [four] s = s[:3] showSliceInfo(s) // panic: runtime error: slice bounds out of range [:3] with capacity 1
簡易スライス式を使う方法
s := []string{"one", "two", "three"} showSliceInfo(s) // len:3 cap:3 0xc00005e000 [one two three] s = s[:0] // クリア showSliceInfo(s) // len:0 cap:3 0xc00005e000 [] s = append(s, "four") showSliceInfo(s) // len:1 cap:3 0xc00005e000 [four] s = s[:3] showSliceInfo(s) // len:3 cap:3 0xc00005e000 [four two three]
完全スライス式を使う方法
s := []string{"one", "two", "three"} showSliceInfo(s) // len:3 cap:3 0xc000098150 [one two three] s = s[:0:3] // クリア showSliceInfo(s) // len:0 cap:3 0xc000098150 [] s = append(s, "four") showSliceInfo(s) // len:1 cap:3 0xc000098150 [four] s = s[:3] showSliceInfo(s) // len:3 cap:3 0xc000098150 [four two three] s = s[:0:0] // クリア showSliceInfo(s) // len:0 cap:0 0xc000098150 [] s = append(s, "five") showSliceInfo(s) // len:1 cap:1 0xc000096250 [five] s = s[:3] showSliceInfo(s) // panic: runtime error: slice bounds out of range [:3] with capacity 1