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)
}
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.
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..
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 .
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With