TRY AND ERROR

気になったこと、勉強したこと、その他雑記など色々メモしていきます。。Sometimes these posts will be written in English.,

【Golang】sliceのcapacityとは?

sliceは可変長の配列を扱うデータ型で、ベースとなる配列のポインタと要素数、および容量(capacity)を持っている。sliceリテラルやmakeはベースとなる配列を作成した上でそのsliceを返している。
sliceは参照型なので、sliceの要素を変更すればベースとなる配列の値も変わる。したがって、sliceのポインタを渡す必要はなく、そのままでもコピーが発生しないのでメモリに優しい。sliceのcapを超えてappendすると参照が外れて、、、ほにゃらら

といった感じのことがブログ等々で書かれているが、容量(capacity)について詳しく触れられているものが見当たらなかったのでメモ。


容量(capacity)というのは、sliceのベース、つまり切り出しもととなる配列において、sliceの最初の要素から配列の最後の要素までの要素数のことである、とのこと。

Slice is a data-type, which has a variable and flexible length, contains pointer, the number of elements, and capacity of its base array.
When you use make or slice literal, the base(underlying) array is allocated and return its slice. Since slice belongs to a type of reference, if the element of slice is changed then the base array's one is changed in the same way.
Therefore besides it's unnecessary to take pointer of slice, it's able to suppress the use of memory. If you append element into slice as over its capacity, its reference of base array get away,,,blah blah blah.
There are many blogs that explain like above, but I hardly find them that explain a definition of 'capacity of slice'. So this time I put a little memo for it.
According to 'Tour of Go', capacity of slice is defined as like the number of element counting from first element of slice to the end of base array's element.


A Tour of Goより

The capacity of a slice is the number of elements in the underlying array, counting from the first element in the slice.

こんな感じ。

s1 := []int{1,2,3,4,5}
// ここで、sliceのベースとなる配列は[1,2,3,4,5]となる
fmt.Println(s1)
fmt.Println(len(s1))
fmt.Println(cap(s1))

/*
	s1: [1,2,3,4,5]
	len(s1): 5
	cap(s1): 5 -> sliceの最初の要素:1 から ベースとなる配列の最後の要素:5 までの要素数(1,2,3,4,5) = 5個
*/

s2 := s1[0:3]
fmt.Println(s2)
fmt.Println(len(s2))
fmt.Println(cap(s2))

/*
	s2: [1,2,3]
	len(s2): 3
	cap(s2): 5 -> sliceの最初の要素:1 からベースとなる配列の最後の要素:5 までの要素数(1,2,3,4,5) = 5個

*/



s3 := s1[2:3]
fmt.Println(s3)
fmt.Println(len(s3))
fmt.Println(cap(s3))

/*
	s3: [3]
	len(s3): 1
	cap(s3): 3 -> sliceの最初の要素:3 からベースとなる配列の最後の要素:5 までの要素数(3,4,5) = 3個

*/