导航

golang 二维动态数组的几个例子

Posted on 2021-07-05 20:00  蝈蝈俊  阅读(625)  评论(0编辑  收藏  举报

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])
    }
}