运行时错误: “在空映射中赋值”

huangapple go评论84阅读模式
英文:

Runtime error: "assignment to entry in nil map"

问题

我试图创建一个Map的切片。虽然代码编译没有问题,但我得到了以下的运行时错误:

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

    //从MySQL的GROUP_CONCAT函数创建数据数组
    inv_ids = strings.Split(row.Str(10), ",")
    inv_names = strings.Split(row.Str(11), ",")
    length := len(inv_ids)

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

    //构建ids => names的Map
    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

    //构建Message并返回
    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)
英文:

I'm trying to create a slice of Maps. Although the code compiles fine, I get the runtime error below:

mapassign1: runtime&#183;panicstring(&quot;assignment to entry in nil map&quot;);

I attempt to make an array of Maps, with each Map containing two indicies, a "Id" and a "Investor". My code looks like this:

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), &quot;,&quot;)
		inv_names = strings.Split(row.Str(11), &quot;,&quot;)
		length := len(inv_ids);

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

		//build map of ids =&gt; names
		for i := 0; i &lt; length; i++ {
			invs[i] = make(map[string]string)
			invs[i][&quot;Id&quot;] = inv_ids[i]
			invs[i][&quot;Investor&quot;] = 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

I initially thought something like below would work, however that did not fix the issue either. Any ideas?

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

答案1

得分: 14

你正在尝试创建一个映射的切片;考虑以下示例:

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])
    }
}
英文:

You are trying to create a slice of maps; consider the following example:

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

package main

import &quot;fmt&quot;

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

You can rewrite these lines:

invs[i] = make(map[string]string)
invs[i][&quot;Id&quot;] = inv_ids[i]
invs[i][&quot;Investor&quot;] = inv_names[i]

as:

invs[i] = map[string]string{&quot;Id&quot;: inv_ids[i], &quot;Investor&quot;: inv_names[i]}

this is called a composite literal.

Now, in a more idiomatic program, you'd most probably want to use a struct to represent an investor:

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

package main

import (
	&quot;fmt&quot;
	&quot;strconv&quot;
)

type Investor struct {
	Id   int
	Name string
}

func main() {
	a := make([]Investor, 100)
	for i := 0; i &lt; 100; i++ {
		a[i] = Investor{Id: i, Name: &quot;John&quot; + strconv.Itoa(i)}
		fmt.Printf(&quot;%#v\n&quot;, a[i])
	}
}

huangapple
  • 本文由 发表于 2013年2月28日 00:43:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/15117513.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定