Reputation: 11469
I've looked up Structs as keys in Golang maps
I understand iteration over the maps in golang has no guaranteed order. I've followed the example in golang blog, and tried using a struct
as a map key.
Here's my code
package main
func main() {
req := make(map[mapKey]string)
req[mapKey{1, "r"}] = "robpike"
req[mapKey{2, "gri"}] = "robert griesemer"
req[mapKey{3, "adg"}] = "andrew gerrand"
req[mapKey{4, "rsc"}] = "russ cox"
var keys []int
for k := range req {
keys = append(keys, k.Key)
}
for _, k := range keys {
fmt.Printf("short name : %s , long name : %s\n",req[k], req[k]) // How do I iterate here
}
sort.Ints(keys)
}
type mapKey struct {
Key int
Option string
}
What I want the results to be is
short name : r , long name : rob pike
short name : gri , long name : robert griesemer
short name : adg , long name : andrew gerrand
short name : rsc , long name : russ cox
And I don't know how I can get the struct value and key iterated by separated data structure.
Upvotes: 0
Views: 12638
Reputation: 99371
Short version? You can't do it that way.
Long version you, you can use a custom sorter:
func main() {
req := make(map[mapKey]string)
req[mapKey{1, "r"}] = "robpike"
req[mapKey{2, "gri"}] = "robert griesemer"
req[mapKey{3, "adg"}] = "andrew gerrand"
req[mapKey{4, "rsc"}] = "russ cox"
var keys mapKeys
for k := range req {
keys = append(keys, k)
}
sort.Sort(keys)
for _, k := range keys {
fmt.Printf("short name : %s , long name : %s\n", k.Option, req[k])
}
}
type mapKey struct {
Key int
Option string
}
type mapKeys []mapKey
func (mk mapKeys) Len() int { return len(mk) }
func (mk mapKeys) Swap(i, j int) { mk[i], mk[j] = mk[j], mk[i] }
func (mk mapKeys) Less(i, j int) bool { return mk[i].Key < mk[j].Key }
Keep in mind that if your mapKey
struct have a field that doesn't support equality (aka a struct or a slice) using req[k]
won't work.
In that case you can switch to type mapKeys []*mapKey
and map[*mapKey]string
.
Upvotes: 3