Home >Backend Development >Golang >How to Fix 'Assignment to Entry in Nil Map' Error When Creating a Slice of Maps in Go?

How to Fix 'Assignment to Entry in Nil Map' Error When Creating a Slice of Maps in Go?

Linda Hamilton
Linda HamiltonOriginal
2024-11-04 14:59:12793browse

How to Fix

Runtime Error: "Assignment to Entry in Nil Map" Resolved

When attempting to create a slice of Maps, you may encounter the runtime error "assignment to entry in nil map." This error indicates that you are trying to access a nil Map value, which is not permitted.

Problem Statement

You are experiencing this error while building an array of Maps, each containing two keys: "Id" and "Investor." The attempted code is as follows:

<code class="go">for _, row := range rows {
    invs := make([]map[string]string, length)

    for i := 0; i < length; i++ {
        invs[i] = make(map[string]string)
        invs[i]["Id"] = inv_ids[i]
        invs[i]["Investor"] = inv_names[i]
    }
}</code>

Resolution

To resolve this error, you should create a slice of Maps directly within the loop instead of creating nil Maps and assigning values to them. This can be achieved using composite literals:

<code class="go">for _, row := range rows {
    invs := make([]map[string]string, length)

    for i := 0; i < length; i++ {
        invs[i] = map[string]string{"Id": inv_ids[i], "Investor": inv_names[i]}
    }
}</code>

Alternative Approach

Alternatively, you can use a struct to represent an investor:

<code class="go">type Investor struct {
    Id       int
    Investor string
}

for _, row := range rows {
    invs := make([]Investor, length)

    for i := 0; i < length; i++ {
        invs[i] = Investor{
            Id:       inv_ids[i],
            Investor: inv_names[i],
        }
    }
}</code>

Using a struct provides a cleaner and more structured representation of your data.

The above is the detailed content of How to Fix 'Assignment to Entry in Nil Map' Error When Creating a Slice of Maps in Go?. 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