Home >Backend Development >Golang >Why Does Assigning to a Map in Go Result in a 'runtime error: assignment to entry in nil map' and How Can It Be Fixed?

Why Does Assigning to a Map in Go Result in a 'runtime error: assignment to entry in nil map' and How Can It Be Fixed?

Susan Sarandon
Susan SarandonOriginal
2024-12-03 22:27:12256browse

Why Does Assigning to a Map in Go Result in a

Runtime Error in Map Assignment

Question:

While attempting to convert a map to a YAML file, an error is encountered stating "runtime error: assignment to entry in nil map." Review the following code snippet:

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

What is causing this error and how can it be resolved?

Answer:

The issue lies in the initialization of the inner map within the outer map. In the example provided, the map m["uid"] is not initialized, resulting in a nil map when attempting to assign the name to it.

To initialize the inner map, add the following line before the for loop:

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

This creates the inner map and allows the name to be assigned to it without encountering a nil map error.

The corrected code becomes:

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

    m := make(map[string]map[string]T, len(names))
    m["uid"] = make(map[string]T) // Initialize the inner map

    for _, name := range names {
        m["uid"][name] = T{cn: "Chaithra", street: "fkmp"}
    }
    fmt.Println(m)

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

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

The above is the detailed content of Why Does Assigning to a Map in Go Result in a 'runtime error: assignment to entry in nil map' and How Can It Be Fixed?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn