Home > Article > Backend Development > Why am I getting a "Runtime Error: Assignment to Entry in Nil Map" while creating a slice of maps in Go?
Runtime Error: "Assignment to Entry in Nil Map" During Slice of Maps Creation
In an attempt to generate a slice of maps, an "assignment to entry in nil map" runtime error arises. Despite the code compiling successfully, this error hampers the program's execution.
The goal is to create an array of maps, with each map containing two indices: "Id" and "Investor." The code attempts this:
<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] } return(msg) }</code>
Initially, an attempt was made to address the problem with the following code:
<code class="go">invs := make([]make(map[string]string), length)</code>
However, it did not resolve the issue.
A Comprehensive Solution
To create a slice of maps effectively, one must employ a different approach. Consider the following example:
<code class="go">package main import "fmt" func main() { a := make([]map[string]int, 100) for i := 0; i < 100; i++ { a[i] = map[string]int{"id": i, "investor": i} } fmt.Println(a) }</code>
Instead of using a loop to assign values to each map, one can use a composite literal:
<code class="go">invs[i] = map[string]string{"Id": inv_ids[i], "Investor": inv_names[i]}</code>
Alternative Solution Using Structs
For a more idiomatic approach, using a struct to represent an investor is advisable:
<code class="go">package main import ( "fmt" " strconv" ) type Investor struct { Id int Name string } func main() { a := make([]Investor, 100) for i := 0; i < 100; i++ { a[i] = Investor{Id: i, Name: "John" + strconv.Itoa(i)} fmt.Printf("%#v\n", a[i]) } }</code>
By employing these techniques, the runtime error can be eliminated, and the desired slice of maps or an array of structs can be obtained, depending on the specific requirements of the program.
The above is the detailed content of Why am I getting a "Runtime Error: Assignment to Entry in Nil Map" while creating a slice of maps in Go?. For more information, please follow other related articles on the PHP Chinese website!