Home >Backend Development >Golang >How to Append Values to Arrays Within Maps in Go?

How to Append Values to Arrays Within Maps in Go?

DDD
DDDOriginal
2024-11-03 21:58:02241browse

How to Append Values to Arrays Within Maps in Go?

Unraveling Array Appends Within Maps in Go

In Go, maps are powerful tools for organizing data. However, it can become tricky when trying to append values to arrays within those maps. Consider a hypothetical scenario:

var MyMap map[string]Example

type Example struct {
    Id []int
    Name []string
}

Puzzle Unveiled

The code snippet attempts to append integers and strings to arrays within a map called MyMap. However, the implementation contains a crucial error:

MyMap["key1"] = Offerty.AppendOffer(1, "SomeText")

Here, Offerty cannot be recognized as an object because it is never defined. To resolve this, create an instance of the Example struct before associating it with the map, as seen below:

obj := &Example{[]int{}, []string{}}
obj.AppendOffer(1, "SomeText")

Reference, Not Copy

Additionally, the code snippet merely creates a copy of the Example struct, not a reference to it. To maintain a pointer to the struct within the map:

MyMap = make(map[string]*Example)
MyMap["key1"] = obj

Solution in Sight

With these modifications, the revised code successfully appends values to arrays within the map:

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)
}

This solution preserves the original Example struct within the map, enabling updates and modifications to its arrays from the outside scope.

The above is the detailed content of How to Append Values to Arrays Within Maps in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn