2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

競プロで使うための GO 入門 ~配列~

Last updated at Posted at 2020-07-17

Index

Arrays(静的配列)の宣言と初期化

  • 固定長でありサイズの変更はできない
  • 初期値は 0
  • Slice より高速
// 宣言
var a [3]int                   // 宣言のみ
var b [3]int = [3]int{4, 5, 6} // 宣言+初期化
c := [...]int{7, 8, 9}         // 動的型付け

// 代入
a[0] = 1
a[1] = 2
a[2] = 3

// 表示
fmt.Printf("a=%d\n", a) // -> a=[1 2 3]
fmt.Printf("b=%d\n", b) // -> b=[4 5 6]
fmt.Printf("b=%d\n", c) // -> c=[7 8 9]

// 要素のみ表示
fmt.Printf("a[0]=%d\n", a[0]) // -> a[0]=1

Slices(動的配列)の宣言と初期化

  • 可変長でありサイズの変更ができる
  • 初期値は Nil
  • Array より低速
  • 宣言のみの場合、要素数を設定 make()または追加 append()する必要がある
	// 宣言
	var a []int                  // 宣言のみ
	var b []int = []int{4, 5, 6} // 宣言+初期化
	c := []int{7, 8, 9}          // 動的型付け

	// 要素数設定
	a = make([]int, 3)

	// 代入
	a[0] = 1
	a[1] = 2
	a[2] = 3

	fmt.Printf("a=%d\n", a) // -> a=[1 2 3]
	fmt.Printf("b=%d\n", b) // -> b=[4 5 6]
	fmt.Printf("b=%d\n", c) // -> c=[7 8 9]

Slice は append() で要素の追加ができる

c = append(c, 10)
fmt.Printf("c=%d\n", c) // -> c=[7 8 9 10]

長さと容量

Allays, Slice ともに、要素数は len() で取得できる

c := [...]int{7, 8, 9}
fmt.Println(len(c)) // -> 3

多次元配列の宣言と初期化

N := 2
M := 3
grid := make([][]int, N)
for i := 0; i < N; i++ {
    grid[i] = make([]int, M)
    for j := 0; j < M; j++ {
        grid[i][j] = j
    }
}
fmt.Println(grid) // ->[[0 1 2] [0 1 2]]

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?