Home > Article > Backend Development > How to Append Values to Arrays Inside Maps in Go?
Appending Values to Arrays Within a Map in Go
When working with maps in Go, manipulating arrays within those maps can be challenging. This article provides a solution to the issue of appending values to arrays stored inside a map.
To understand the problem, consider the following code:
<code class="go">type Example struct { Id []int Name []string } var MyMap map[string]Example</code>
Here, the MyMap is a map that maps strings to instances of the Example struct. The Example struct contains arrays Id and Name. The goal is to append values to these arrays.
The initial attempt to do this often involves calling methods on the Example struct and passing a pointer receiver to access and modify the arrays. However, directly assigning the result of Oferty.AppendExample(1, "SomeText") to MyMap["key1"] will not work because the map stores a copy of the Example struct, not the struct itself.
The solution lies in modifying the code as follows:
<code class="go">package main import "fmt" type Example struct { Id []int Name []string } func (data *Example) AppendOffer(id int, name string) { data.Id = append(data.Id, id) data.Name = append(data.Name, name) } var MyMap map[string]*Example func main() { obj := &Example{[]int{}, []string{}} obj.AppendOffer(1, "SomeText") MyMap = make(map[string]*Example) MyMap["key1"] = obj fmt.Println(MyMap) }</code>
By creating an instance of the Example struct and storing a reference to it in the map (using a pointer type), we can modify the arrays directly. The AppendOffer method operates on a pointer to the Example struct, allowing us to append values to the arrays.
This solution effectively appends values to the arrays within the Example struct, stored in the MyMap. It provides a clear and concise approach to managing arrays inside maps in Go.
The above is the detailed content of How to Append Values to Arrays Inside Maps in Go?. For more information, please follow other related articles on the PHP Chinese website!