0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Goのスライスを理解する(基本)

0
Posted at

1. スライスとは?

スライスは 可変長の配列のようなもの です。

var i []int
fmt.Println(cap(i))// 0

ポイント

  • var i []intnilスライス
  • 長さ(len)も容量(cap)も 0

2. スライスの初期化

リテラルで作る

var a []int = []int{100,200}
fmt.Println(a)// [100 200]

b := []string{"A","B"}
fmt.Println(b)// [A B]

make で作る

l := make([]int,0,5)
fmt.Println(l) // []

make の意味

make([]int, 長さ, 容量)
  • 長さ(len)= 0
  • 容量(cap)= 5

→ この「容量」は append で使える


3. スライスは参照型

a[0] =1000
fmt.Println(a)// [1000 200]

スライスは内部で 配列を参照している構造体 です。

つまり、

  • コピーしても
  • 別のスライスを作っても

元の配列を共有している可能性があります


4. スライス式(部分取得)

d := []int{1,2,3,4,5,6}
fmt.Println(d)// [1 2 3 4 5 6]

4-1. 単一要素取得

fmt.Println(d[0])// 1

4-2. 範囲指定 [i:j]

fmt.Println(d[2:4])// [3 4]

意味:

  • 開始インデックス含む(2)
  • 終了インデックス含まない(4)

つまり:

index: 0 1 2 3 4 5value: 1 2 3 4 5 6

d[2:4] → index 2,3 → [3 4]


4-3. 先頭から

fmt.Println(d[:2])// [1 2]

= d[0:2]


4-4. 途中から最後まで

fmt.Println(d[2:])// [3 4 5 6]

= d[2:len(d)]


4-5. 全体

fmt.Println(d[:])// [1 2 3 4 5 6]

4-6. 最後の要素

fmt.Println(d[len(d)-1])// 6

4-7. 先頭と末尾を除く

fmt.Println(d[1 :len(d)-1])// [2 3 4 5]

5. スライス式のルールまとめ

書き方 意味
a[i:j] i以上 j未満
a[:j] 0以上 j未満
a[i:] i以上 末尾まで
a[:] 全体

👉(重要) 終端は含まない


6. スライスの内部構造(ざっくり)

スライスは内部的に:

  • 配列へのポインタ
  • 長さ(len)
  • 容量(cap)

を持つ構造体です。

だから:

  • len() は現在の長さ
  • cap() は確保されている容量

7. まとめ

  • スライスは可変長の配列
  • make([]T, len, cap) で作れる
  • スライスは参照型
  • [i:j] は「i以上 j未満」
  • len(d)-1 で最後の要素

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?