我正在尝试制作一片地图。虽然代码编译得很好,但我得到下面的运行时错误:
mapassign1: runtime·panicstring("assignment to entry in nil map");
我尝试制作一个地图数组,每个地图包含两个指标,一个“Id”和一个“投资者”。我的代码如下所示:
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)
答案 0 :(得分:11)
您正在尝试创建切片地图;请考虑以下示例:
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]}
这称为复合文字。
现在,在一个更惯用的程序中,你很可能想用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])
}
}