运行时错误:对空映射中的条目进行赋值

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

Runtime error: assignment to entry in nil map

问题

我正在尝试生成一个地图,然后将其转换为以下格式的yaml文件:

uid :
      kasi:
        cn: Chaithra
        street: fkmp
      nandan:
        cn: Chaithra
        street: fkmp
      remya:
        cn: Chaithra
        street: fkmp

我觉得在创建地图时可能漏掉了一些重要的东西。我的代码如下:

package main

import (
	"fmt"
	"gopkg.in/yaml.v2"
)

type T struct {
	cn     string
	street string
}

func main() {
	names := []string{"kasi", "remya", "nandan"}

	m := make(map[string]map[string]T, len(names))
	for _, name := range names {

		//t := T{cn: "Chaithra", street: "fkmp"}

		m["uid"][name] = T{cn: "Chaithra", street: "fkmp"}

	}
	fmt.Println(m)

	y, _ := yaml.Marshal(&m)

	fmt.Println(string(y))
	//fmt.Println(m, names)
}

它给出了以下错误:

panic: runtime error: assignment to entry in nil map
英文:

I am trying to generate a map and then convert that to a yaml file like this:

uid :
      kasi:
        cn: Chaithra
        street: fkmp
      nandan:
        cn: Chaithra
        street: fkmp
      remya:
        cn: Chaithra
        street: fkmp

I think I am missing something important while creating the map. My code is below.

package main

import (
	"fmt"
	"gopkg.in/yaml.v2"
)

type T struct {
	cn     string
	street string
}

func main() {
	names := []string{"kasi", "remya", "nandan"}

	m := make(map[string]map[string]T, len(names))
	for _, name := range names {

		//t := T{cn: "Chaithra", street: "fkmp"}

		m["uid"][name] = T{cn: "Chaithra", street: "fkmp"}

	}
	fmt.Println(m)

	y, _ := yaml.Marshal(&m)

	fmt.Println(string(y))
	//fmt.Println(m, names)
}

It is giving the following error:

panic: runtime error: assignment to entry in nil map

答案1

得分: 191

你还没有初始化你的内部映射。在你的for循环之前,你可以添加m["uid"] = make(map[string]T),然后赋值名称。

英文:

You have not initialized your inner map. Before your for loop you can add m["uid"] = make(map[string]T) and then assign the name.

答案2

得分: 34

你应该检查地图是否为nil,并在for循环内部如果为nil则初始化一个:

if m["uid"] == nil {
	m["uid"] = map[string]T{}
}
英文:

You should check if the map is nil and initialize one if it's nil inside the for loop:

if m["uid"] == nil {
	m["uid"] = map[string]T{}
}

答案3

得分: 20

你可能使用了变量 var m map[string]interface{} 来定义地图。

相反,可以使用 m := make(map[string]interface{}) 来避免相应的错误。

英文:

Probably the map you have define is by using variable
var m map[string]interface{}

Instead use
m := make(map[string]interface{})
to avoid respective error

答案4

得分: 9

根据错误信息 "assignment to entry in nil map",在嵌套的地图中,当给深层级键赋值时,我们需要确保其外部键具有值。否则,它会报告地图为nil。例如,在您的情况下:

m := make(map[string]map[string]T, len(names))

m是一个嵌套地图,它包含一个string键和一个值为map[string]T的值。您正在赋值:

m["uid"][name] = T{cn: "Chaithra", street: "fkmp"}

在这里,您可以看到m["uid"]nil,我们正在声明它包含一个值[name],它是类型为T的嵌套值的键。因此,您首先需要给"uid"赋值或将其初始化为:

m["uid"] = make(map[string]T)
英文:

There is thing as per the error

assignment to entry in nil map

For nested maps when assign to the deep level key we needs to be certain that its outer key has value. Else it will say that the map is nil. For eg in your case

m := make(map[string]map[string]T, len(names))

m is a nested map which contains string key with map[string]T as value. And you are assign the value

m["uid"][name] = T{cn: "Chaithra", street: "fkmp"}

here you can see the m["uid"] is nil and we are stating it contains a value [name] which is a key to nested value of type T. So first you need to assign value to "uid" or initialise it as

m["uid"] = make(map[string]T)

答案5

得分: 2

@Makpoc已经回答了这个问题,我只是添加了一些额外的信息。

> Map类型是引用类型,类似于指针或切片,所以上面的m的值是nil;它没有指向一个初始化的map。当读取时,nil map的行为类似于空map,但是尝试向nil map写入将导致运行时恐慌;不要这样做。关于Map的更多信息

英文:

@Makpoc already answered the question. just adding some extra info.

> Map types are reference types, like pointers or slices, and so the value of m above is nil; it doesn't point to an initialized map. A nil map behaves like an empty map when reading, but attempts to write to a nil map will cause a runtime panic; don't do that. more info about Map

huangapple
  • 本文由 发表于 2014年12月3日 17:26:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/27267900.html
匿名

发表评论

匿名网友

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

确定