nemunemu_zzzの日記

備忘録的な何かになればいいな

golang 2次元スライス

よくスライスの作り方を忘れてしまうのでメモメモ

空の2次元スライス

    
    var s2 [][]int
    // or
    s2 := [][]int{} //後ろの{} 忘れ注意

確認

    fmt.Println(s2) # => []
    ftm.Println(reflect(s2)) # => [][]int

出力は空のスライスに見えるが、型はちゃんと2次元になっている

スライスの要素追加は append を使用する

    s := []int{1, 2, 3}
    s2 = append(s2, s)
    fmt.Println(s2)       # => [ [1 2 3] ]
    fmt.Println(s2[0])    # => [1 2 3]
    fmt.Println(s2[0][0]) # => 1