Home > Backend Development > Golang > How to Resolve the 'Assignment to Entry in Nil Map Error' During Slice Initialization in Go?

How to Resolve the 'Assignment to Entry in Nil Map Error' During Slice Initialization in Go?

Linda Hamilton
Release: 2024-11-05 11:37:02
Original
543 people have browsed it

How to Resolve the

Assignment to Entry in Nil Map Error During Slice Initialization

This runtime error occurs when assigning to a nil map entry within a slice. In the provided code, the error originates from an attempt to create a slice of maps.

To rectify this issue, the approach should be modified as follows:

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

var invs []Investor

for _, row := range rows {
    var inv_ids []string
    var inv_names []string

    // Create arrays of data from MySQL GROUP_CONCAT function
    inv_ids = strings.Split(row.Str(10), ",")
    inv_names = strings.Split(row.Str(11), ",")

    // Build slice of investors
    for i := 0; i < len(inv_ids); i++ {
        invs = append(invs, Investor{inv_ids[i], inv_names[i]})
    }
}</code>
Copy after login

Here, we define a custom Investor struct to represent each map entry. We then initialize invs as a slice of Investor structs and populate it within the loop. This approach avoids the use of nil maps and ensures proper assignment of values.

An alternative option presented in the provided answer involves using composite literals to initialize the maps directly within the slice. This can be achieved as follows:

<code class="go">var invs []map[string]string

for _, row := range rows {
    var inv_ids []string
    var inv_names []string

    // Create arrays of data from MySQL GROUP_CONCAT function
    inv_ids = strings.Split(row.Str(10), ",")
    inv_names = strings.Split(row.Str(11), ",")

    // Build slice of maps
    for i := 0; i < len(inv_ids); i++ {
        invs = append(invs, map[string]string{"Id": inv_ids[i], "Investor": inv_names[i]})
    }
}</code>
Copy after login

The above is the detailed content of How to Resolve the 'Assignment to Entry in Nil Map Error' During Slice Initialization in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template