LoginSignup
0
0

More than 1 year has passed since last update.

【備忘録】Golangでスライスを利用する。

Posted at

Golangで1次元スライスを利用する

main.go
package main

import "fmt"

func main(){
	// 1次元スライス
	s1 := []int{1, 2, 3}
    s2 := []int{5, 6, 7}

	// 1次元スライスに要素を追加する。
	s1 = append(s1, 4)

	fmt.Println("s1: ",s1)

	// 1次元スライスに1次元スライスを追加する。
    s1 = append(s1, s2...)

    fmt.Println("s1: ", s1)
}
実行結果
~/go/src/array_slice $ go run main.go
s1:  [1 2 3 4]
s1:  [1 2 3 4 5 6 7]

Golangで2次元スライスを利用する

main.go
package main

import (
	"fmt"
)

func main() {
    s1 := [][]int{{1, 1}, {1, 2}, {1, 3}}
	fmt.Println("s1:", append(s1, []int{1,4})) // 追加時に[]int{}とする所に注意!!

	s2 := [][]int{{2, 1}, {2, 2}, {2, 3}}
    s1 = append(s1, s2...)
	fmt.Println("s1: ", s1)
}
実行結果
~/go/src/array_slice $ go run main.go
s1: [[1 1] [1 2] [1 3] [1 4]]
s1:  [[1 1] [1 2] [1 3] [2 1] [2 2] [2 3]]

おまけ:配列とスライスの違い。

配列は固定長、スライスは可変長で定義されている。Javaで言うスライスはList、配列は配列となる。
可変長で利用できる方が便利だから、なぜ配列が利用されるのかと言うのは誰しも思う疑問。
その答えは公式のドキュメントで答えが書いてありました。興味のある人は読んでみてね!!!

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