Programing

런타임 오류 : nil 맵의 항목에 할당

lottogame 2020. 10. 8. 07:36
반응형

런타임 오류 : nil 맵의 항목에 할당


지도를 생성 한 다음 다음과 같이 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

내부지도를 초기화하지 않았습니다. for 루프 전에 m["uid"] = make(map[string]T)이름을 추가 한 다음 할당 할 수 있습니다 .


맵이 nil인지 확인하고 for 루프 내에서 nil이면 초기화해야합니다.

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

오류에 따른 것이 있습니다

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

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)

@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

참고URL : https://stackoverflow.com/questions/27267900/runtime-error-assignment-to-entry-in-nil-map

반응형