Appending Values to Array within a Map in Go
When attempting to append values to arrays within a map, you may encounter difficulties setting references to Example objects.
In Go, the following code attempts to append values to an Example struct:
<code class="go">var MyMap map[string]Example type Example struct { Id []int Name []string } package main import ( "fmt" ) type Example struct { Id []int Name []string } func (data *Example) AppendExample(id int,name string) { data.Id = append(data.Id, id) data.Name = append(data.Name, name) } var MyMap map[string]Example func main() { MyMap = make(map[string]Example) MyMap["key1"] = Oferty.AppendExample(1,"SomeText") fmt.Println(MyMap) }</code>
However, this code is incorrect for several reasons:
The following corrected code addresses these issues:
<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>
In this corrected code:
By implementing these corrections, the code correctly appends values to the arrays within the map while preserving object references.
The above is the detailed content of How do you append values to arrays within a map in Go while preserving object references?. For more information, please follow other related articles on the PHP Chinese website!