Home > Article > Backend Development > How to Avoid 'Assignment to Entry in Nil Map' Runtime Error When Working with Slices of Maps in Go?
Runtime Error: "Assignment to Entry in Nil Map"
When working with slices of maps, it's crucial to avoid creating a slice of nil maps, which will result in a runtime error like the one you encountered.
To create a slice of maps, follow these steps:
Make a slice of maps with the make() function:
<code class="go">invs := make([]map[string]string, length)</code>
Populate the maps within the slice:
<code class="go">for i := 0; i < length; i++ { invs[i] = map[string]string{"Id": inv_ids[i], "Investor": inv_names[i]} }</code>
Consider using a Composite Literal:
Instead of creating a nil map and assigning values to it, you can use a composite literal, which combines all the key-value pairs into a single expression:
<code class="go">invs[i] = map[string]string{"Id": inv_ids[i], "Investor": inv_names[i]}</code>
Alternative Approach Using a Struct:
An alternative and more idiomatic approach is to define a struct to represent an investor and use a slice of structs:
<code class="go">type Investor struct { Id int Name string } invs := make([]Investor, length) for i := 0; i < length; i++ { invs[i] = Investor{Id: i, Name: "John" + strconv.Itoa(i)} }</code>
The above is the detailed content of How to Avoid 'Assignment to Entry in Nil Map' Runtime Error When Working with Slices of Maps in Go?. For more information, please follow other related articles on the PHP Chinese website!