HiveBrain v1.2.0
Get Started
← Back to all entries
debuggoCritical

Runtime error: assignment to entry in nil map

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
maperrornilruntimeassignmententry

Problem

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

Solution

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.

Context

Stack Overflow Q#27267900, score: 207

Revisions (0)

No revisions yet.