1. 程式人生 > 其它 >golang 二維動態陣列的幾個例子

golang 二維動態陣列的幾個例子

https://blog.csdn.net/qq_37822034/article/details/107405871

package main
 
import (
    "fmt"
)
 
func main() {
    n := 2
    m := 3
    //動態建立二維陣列
    grid := make([][]int, n)
    for i := 0; i < n; i++ {
        grid[i] = make([]int, m)
    }
    /*
        000
        000
    */
    for i := 0; i < n; i++ {
        for j := 0; j < m; j++ {
            fmt.Print(grid[i][j])
        }
        fmt.Println()
    }
}

https://www.cnblogs.com/mysticbinary/p/13355401.html

func main() {
    var array1 [][]string
    var tmp []string

    tmp = append(tmp, "001")
    tmp = append(tmp, "002")

    array1 = append(array1, tmp)

    fmt.Println(array1)
    fmt.Println(array1[0])
    fmt.Println(array1[0][1])
}

https://www.runoob.com/go/go-multi-dimensional-arrays.html

package main

import "fmt"

func main() {
    // 建立空的二維陣列
    animals := [][]string{}

    // 建立三一維陣列,各陣列長度不同
    row1 := []string{"fish", "shark", "eel"}
    row2 := []string{"bird"}
    row3 := []string{"lizard", "salamander"}

    // 使用 append() 函式將一維陣列新增到二維陣列中
    animals = append(animals, row1)
    animals = append(animals, row2)
    animals = append(animals, row3)

    // 迴圈輸出
    for i := range animals {
        fmt.Printf("Row: %v\n", i)
        fmt.Println(animals[i])
    }
}