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
Release: 2024-11-03 21:58:02
Original
203 people have browsed it

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
}
Copy after login

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")
Copy after login

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")
Copy after login

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
Copy after login

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)
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template