一尘不染

运行时错误:“在nil映射中分配给条目”

go

我正在尝试创建地图片段。尽管代码可以很好地编译,但在下面出现运行时错误:

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

我尝试制作一个Map数组,每个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)

阅读 231

收藏
2020-07-02

共1个答案

一尘不染

您正在试图建立一个 切片 地图; 考虑以下示例:

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

这称为 复合文字

现在,在一个更加惯用的程序中,您很可能想使用a struct代表投资者:

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])
    }
}
2020-07-02