1
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入門 #03:配列とスライスの違いと使い分け

Posted at

配列とスライスとは

観点 配列 [N]T スライス []T
型の定義 長さを含む([3]int[4]int は別型) 長さを含まない([]int は共通)
可変長か 固定長(変更不可) 可変長(append で拡張可能)
型の分類 値型 参照型
利用頻度 ほとんど使われない(内部処理や特殊用途のみ) 実務で一般的に使用される

宣言、初期化の違い

方法 配列 [N]T スライス []T
宣言(空) var a [3]int var s []int
リテラル初期化 a := [3]int{1, 2, 3} s := []int{1, 2, 3}
長さ推論 a := [...]int{1, 2, 3}(コンパイル時に決定) なし(スライスは可変長)
makeによる生成 使えない s := make([]int, 3)(長さ3のスライスを作る)

使い分け

特に何もなければスライスを使います
決まった目的(固定長、外部API互換、低レベル最適化など)がある時だけ配列を使います。

まとめ

配列は固定長で値を直接持つのに対し、スライスは配列を参照する柔軟な型です。
普段はスライスを使い、固定長や特殊な用途でのみ配列を使います。

1
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
1
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?