How to Append Values to Arrays Inside Maps in Go?

DDD
Release: 2024-11-02 02:53:30
Original
990 people have browsed it

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

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!