12

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)
}
1
  • I thought i solved the problem but what i did does not solve it as i need to assign value on the key matching in a loop. Commented Nov 11, 2017 at 17:16

2 Answers 2

16

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!

Sign up to request clarification or add additional context in comments.

3 Comments

Yeah, i did exactly the same thing as well as i couldn't find how to do without creating an object of struct. I will undelete my own answer. Thank you for input!
Not really the same. You're still using struct literal instead of a pointer in your map. Please read more about structs and pointers here: gobyexample.com/pointers gobyexample.com/structs
instead of obj := &Example{[]int{}, []string{}} use obj1 := new(Example) see Exampe in Go Playground
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.