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>
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>
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!