Append values to array inside of map golang

Viewed 36595

I am trying to append values to arrays inside of a map:

var MyMap map[string]Example 

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

Here is what i tried but i can not point to an object of Example to append to arrays.

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

You need to create an instance of your Example struct before putting it into the map.

Also your map keeps copy of your struct, not a struct itself according to MyMap definition. Try to keep the reference to your Example struct within the map instead.

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

Pozdrawiam!

Okay, i solved it by creating an Example object and then appending values to its array and assigning it to map.

Like this:

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() {

  var object Example
  object.AppendExample(1,"SomeText")

  MyMap = make(map[string]Example)
  MyMap["key1"] = object
  fmt.Println(MyMap)
}
Related