鍍金池/ 問答/GO/ 請問go語言的多維數(shù)組怎么寫

請問go語言的多維數(shù)組怎么寫

比如在php中:

$a[0]["title"]="a";
$a[0]["desc"]="hello";

在go語言中,應該如何申請和賦值,我查了些資料一直沒能成功。

請幫我寫一個演示一下,實現(xiàn)和上面php代碼一樣的數(shù)據(jù)結構,謝謝。

回答
編輯回答
薔薇花

以二維數(shù)組舉例:

type Matrix [][]int

func constructMatrix(rows, cols int) Matrix {
    m := make([][]int, rows)
    for i := 0; i < rows; i++ {
        m[i] = make([]int, cols)
    }
    return m
}
2017年3月26日 20:16
編輯回答
風清揚

題中的結構更像是map組成的數(shù)組

package main

import "fmt"

func main() {
    //問題的場景
    a := make([]map[string]string, 1)
    a[0] = make(map[string]string)
    a[0]["title"] = "a"
    a[0]["desc"] = "hello"
    fmt.Printf("value is %+v\n", a)

    //多維數(shù)組
    b := make([][2]string, 1)
    b[0][0] = "a"
    b[0][1] = "hello"
    fmt.Printf("value is %+v\n", b)

    //個人更推薦的方式, 更清晰易擴展
    c := make([]struct {
        Title string
        Desc  string
    }, 1)
    c[0].Title = "a"
    c[0].Desc = "hello"
    fmt.Printf("value is %+v\n", c)
}
2017年4月20日 18:31