0
0

More than 1 year has passed since last update.

[Go][備忘録] sliceをmake()する方法による挙動の違い

Posted at

はじめに

Go初心者です。
学習していて、今後つまずきそうと思ったのでメモしておきます。

make()方法による挙動の違い

make()を使用してsliceを作成する場合、第2引数にlength、第3引数にcapacityを渡すようにしないと、intの初期値である0で埋められたsliceが作成されてしまう。

make()にsizeだけ渡す場合

package main

import "fmt"

func main() {
	var s []int
	s = make([]int, 5)

	for i := 0; i < 5; i++ {
		s = append(s, i)
		fmt.Println(s)
	}
	fmt.Println(s)
    // -> [0 0 0 0 0 0 1 2 3 4]
}

make()にsizeとcapcityどちらも渡す場合

package main

import "fmt"

func main() {
	var s []int
-	s = make([]int, 5)
+   s = make([]int, 0, 5)

	for i := 0; i < 5; i++ {
		s = append(s, i)
		fmt.Println(s)
	}
	fmt.Println(s)
    // -> [0 1 2 3 4]
}

まあ、make()関数の説明にハッキリ明言されてるし大丈夫か...?

Slice: The size specifies the length. The capacity of the slice is
equal to its length. A second integer argument may be provided to
specify a different capacity; it must be no smaller than the
length.

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0