LoginSignup
0
0

More than 1 year has passed since last update.

[Golang] スライス、キャパシティ、初期値

Posted at

変数の設定による違いを理解する

コード

main.go
package main

import (
	"fmt"
)

func main() {
	calc()
}

func calc() {
	var b []int              // 初期値はnilの[]スライス
	c := make([]int, 5)      // 初期値は[0 0 0 0 0]のスライス
	d := make([]int, 0, 5)   // 初期値は空の[]スライス

	fmt.Println("/-- 初期値 --/")
	fmt.Println(b)
	fmt.Println(c)
	fmt.Println(d)

	for i := 0; i < 5; i++ {
		b = append(b, i)
		c = append(c, i)
		d = append(d, i)
		fmt.Printf("/-- %d times --/ \n", i)
		fmt.Println(b)
		fmt.Println(c)
		fmt.Println(d)
	}
}

実行結果

/-- 初期値 --/
[]
[0 0 0 0 0]
[]
/-- 0 times --/ 
[0]
[0 0 0 0 0 0]
[0]
/-- 1 times --/ 
[0 1]
[0 0 0 0 0 0 1]
[0 1]
/-- 2 times --/ 
[0 1 2]
[0 0 0 0 0 0 1 2]
[0 1 2]
/-- 3 times --/ 
[0 1 2 3]
[0 0 0 0 0 0 1 2 3]
[0 1 2 3]
/-- 4 times --/ 
[0 1 2 3 4]
[0 0 0 0 0 0 1 2 3 4]
[0 1 2 3 4]

まとめ

変数設定の結果

func calc() {
	var b []int
	c := make([]int, 5)
	d := make([]int, 0, 5)
  • 変数bは、初期値はnilになり、空の[ ]スライス
  • 変数cは、初期値は[0 0 0 0 0]のスライス
  • 変数dは、初期値は空の[ ]スライス
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