So, I am confused. I am coming from a Python background and trying to learn Go. So, in Python I can do:
age_dict = {}
age_dict[40] = []
age_dict[40].append(MyData(someone)
age_dict[40].append(MyData(someonelse))
age_dict[2] = [MyData(kid)]
This would produce:
{2: [<MyData object at 0x7fea79de96d0>],
40: [<MyData object at 0x7fea79de9ed0>, <MyData object at 0x7fea79de9e10>]}
This would give me a dictionary (read: map) which has an integer as a key and has a list (read:array) of values. I would like to do something similar in Go, but I am just not getting it.
type MyData struct {
name string
age int8
}
age_map = map[int][]MyData
age_map[40].append(age_map[40], MyData{"someone", 40})
age_map[40].append(age_map[40], MyData{"someone", 40})
So, what am I doing wrong? I am just not understanding how to do this - if it's possible at all. My real issue is understanding the whole:
map[int][]MyCustomType
Syntax. Can someone point me in the correct direction?
评论:
anaerobic_lifeform:
Kraigius:The new slice is given by the return value of "append".
TheMerovius:To expand and to help avoid a common pitfall when starting go, a slice is basically a view on an array. 98% of the time when appending, you will want to assign the result back to the very same slice, this isn't a new variable. The view changed but it's using the same array in the back.
When you append you add something at
s[len(s)]
of the view. If you start to assign the result of an append to a different slice you will end up overwriting values.Demonstration: https://play.golang.org/p/xlQZs7uyNf
This might seems like I'm throwing random knowledge that isn't related to OP problem at hand but it's such a common pitfall when starting using slice and it isn't well communicated that I just want to share it.
TheMerovius:Does this help a bit?
to explain:
map[int][]MyData
is a type, read it as: "map
fromint
to slice of ([]
)MyData
"make(T)
will create a new value of typeT
- in this case, above map. So it's equivalent to the{}
from the first line of your python code, just statically typedage_map := …
declares a new variable with nameage_map
and assigns…
to it. See the spec for details.- In Go,
append
is not a method on slices (which is the correct equivalent of a python list; in Go, an array has a fixed length and is something different). Instead, there is a builtin functionappend
, which takes a slice and some elements and returns the slice with the elements appended. So, it doesn't work in-place and you need to assign the return value to use it.
This did it. I was confused by the append syntax. Many, many thanks.
