15

我正在尝试创建一片地图。虽然代码编译得很好,但我得到下面的运行时错误:

mapassign1: runtime·panicstring("assignment to entry in nil map");

我尝试制作一个地图数组,每个地图包含两个指标,一个“Id”和一个“Investor”。我的代码如下所示:

for _, row := range rows {
        var inv_ids []string
        var inv_names []string

        //create arrays of data from MySQLs GROUP_CONCAT function
        inv_ids = strings.Split(row.Str(10), ",")
        inv_names = strings.Split(row.Str(11), ",")
        length := len(inv_ids);

        invs := make([]map[string]string, length)

        //build map of ids => names
        for i := 0; i < length; i++ {
            invs[i] = make(map[string]string)
            invs[i]["Id"] = inv_ids[i]
            invs[i]["Investor"] = inv_names[i]
        }//for

        //build Message and return
        msg := InfoMessage{row.Int(0), row.Int(1), row.Str(2), row.Int(3), row.Str(4), row.Float(5), row.Float(6), row.Str(7), row.Str(8), row.Int(9), invs}
        return(msg)
    } //for

我最初认为像下面这样的东西会起作用,但这也不能解决问题。有任何想法吗?

invs := make([]make(map[string]string), length)
4

1 回答 1

13

您正在尝试创建一片地图;考虑以下示例:

http://play.golang.org/p/gChfTgtmN-

package main

import "fmt"

func main() {
    a := make([]map[string]int, 100)
    for i := 0; i < 100; i++ {
        a[i] = map[string]int{"id": i, "investor": i}
    }
    fmt.Println(a)
}

您可以重写这些行:

invs[i] = make(map[string]string)
invs[i]["Id"] = inv_ids[i]
invs[i]["Investor"] = inv_names[i]

作为:

invs[i] = map[string]string{"Id": inv_ids[i], "Investor": inv_names[i]}

这称为复合文字

现在,在一个更惯用的程序中,您很可能希望使用 astruct来代表投资者:

http://play.golang.org/p/vppK6y-c8g

package main

import (
    "fmt"
    "strconv"
)

type Investor struct {
    Id   int
    Name string
}

func main() {
    a := make([]Investor, 100)
    for i := 0; i < 100; i++ {
        a[i] = Investor{Id: i, Name: "John" + strconv.Itoa(i)}
        fmt.Printf("%#v\n", a[i])
    }
}
于 2013-02-27T17:15:46.130 回答