Home  >  Article  >  Backend Development  >  How do you append values to arrays within a map in Go while preserving object references?

How do you append values to arrays within a map in Go while preserving object references?

Barbara Streisand
Barbara StreisandOriginal
2024-11-01 21:28:29902browse

How do you append values to arrays within a map in Go while preserving object references?

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:

  • Initialization Error: Oferty is an undefined variable.
  • Instance Creation: An instance of Example must be created before adding it to the map.
  • Map Reference Issue: The map MyMap should contain references to Example instances, not copies.

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 := &amp;Example{[]int{}, []string{}}
    obj.AppendOffer(1, "SomeText")
    MyMap = make(map[string]*Example)
    MyMap["key1"] = obj
    fmt.Println(MyMap)
}</code>

In this corrected code:

  • An instance of Example (obj) is created before adding it to the map.
  • The map MyMap contains references to Example instances using pointers (*Example).
  • The method AppendOffer is used to append values to the array fields of the Example instance.

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!

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