LoginSignup
0
0

More than 1 year has passed since last update.

Go言語 スライス

Posted at

スライス

可変長配列を表す型。
配列と違い、スライスは要素の追加が出来る。

Code

func main() {
	// スライスの生成
	tenSlice := make([]int, 10)
	fmt.Println(tenSlice)

	// 要素への代入
	tenSlice[0] = 123
	tenSlice[3] = 456
	tenSlice[6] = 789
	fmt.Println(tenSlice)

	// 値の参照
	fmt.Println(tenSlice[0])
	fmt.Println(tenSlice[1])

	// スライスの要素数
	fmt.Println(len(tenSlice))

	// スライスの容量
	fmt.Println(cap(tenSlice))

	// 簡易スライス式
	fiveSlice := tenSlice[2:7]
	fmt.Println(fiveSlice)

	// 要素の拡張
	elevenSlice := append(tenSlice, 101112)
	fmt.Println(elevenSlice)

	// 完全スライス式
	fullSlice := tenSlice[1:7:8]
	fmt.Println(fullSlice)

	// forによる出力
	for i, s := range tenSlice {
		fmt.Println(strconv.Itoa(i)+" : "+strconv.Itoa(s))
	}
}

Output Sample

~ $ go build slice.go
~ $ ./slice
[0 0 0 0 0 0 0 0 0 0]
[123 0 0 456 0 0 789 0 0 0]
123
0
10
10
[0 456 0 0 789]
[123 0 0 456 0 0 789 0 0 0 101112]
[0 0 456 0 0 789]
0 : 123
1 : 0
2 : 0
3 : 456
4 : 0
5 : 0
6 : 789
7 : 0
8 : 0
9 : 0

GitHub

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