Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append values to array inside of map golang

Tags:

go

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)
}
like image 699
Saem Avatar asked Nov 11 '17 16:11

Saem


People also ask

Can you append to an array in Golang?

There is no way in Golang to directly append an array to an array. Instead, we can use slices to make it happen. The following characteristics are important to note: Arrays are of a fixed size.

How do I iterate over a map in Golang?

You can iterate through a map in Golang using the for... range statement where it fetches the index and its corresponding value. In the code above, we defined a map storing the details of a bookstore with type string as its key and type int as its value. We then looped through its keys and values using the for..

How do I add a slice in Golang?

To add an element to a slice , you can use Golang's built-in append method. append adds elements from the end of the slice. The first parameter to the append method is a slice of type T . Any additional parameters are taken as the values to add to the given slice .


1 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!

like image 162
Bohdan Kostko Avatar answered Sep 19 '22 21:09

Bohdan Kostko