Runtime error: assignment to entry in nil map

前端 未结 4 1075
逝去的感伤
逝去的感伤 2021-01-31 12:53

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

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


        
相关标签:
4条回答
  • 2021-01-31 13:43

    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.

    0 讨论(0)
  • 2021-01-31 13:47

    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)
    
    0 讨论(0)
  • 2021-01-31 13:47

    @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

    0 讨论(0)
  • 2021-01-31 13:52

    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{}
    }
    
    0 讨论(0)
提交回复
热议问题