在 golang 中迭代 Struct(映射键)值

我在 Golang 地图中查找结构作为键


我知道在 golang 中对地图的迭代没有保证的顺序。我遵循了golang blog 中的示例,并尝试使用 astruct作为映射键。


这是我的代码


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

}

我想要的结果是


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

而且我不知道如何获得由分离的数据结构迭代的结构值和键。


呼如林
浏览 137回答 1
1回答

青春有我

精简版?你不能那样做。长版你,你可以使用自定义排序器:func main() {&nbsp; &nbsp; req := make(map[mapKey]string)&nbsp; &nbsp; req[mapKey{1, "r"}] = "robpike"&nbsp; &nbsp; req[mapKey{2, "gri"}] = "robert griesemer"&nbsp; &nbsp; req[mapKey{3, "adg"}] = "andrew gerrand"&nbsp; &nbsp; req[mapKey{4, "rsc"}] = "russ cox"&nbsp; &nbsp; var keys mapKeys&nbsp; &nbsp; for k := range req {&nbsp; &nbsp; &nbsp; &nbsp; keys = append(keys, k)&nbsp; &nbsp; }&nbsp; &nbsp; sort.Sort(keys)&nbsp; &nbsp; for _, k := range keys {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("short name : %s , long name : %s\n", k.Option, req[k])&nbsp; &nbsp; }}type mapKey struct {&nbsp; &nbsp; Key&nbsp; &nbsp; int&nbsp; &nbsp; Option string}type mapKeys []mapKeyfunc (mk mapKeys) Len() int&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;{ return len(mk) }func (mk mapKeys) Swap(i, j int)&nbsp; &nbsp; &nbsp; { mk[i], mk[j] = mk[j], mk[i] }func (mk mapKeys) Less(i, j int) bool { return mk[i].Key < mk[j].Key }play请记住,如果您的mapKey结构有一个不支持相等的字段(又名结构或切片),则 usingreq[k]将不起作用。在这种情况下,您可以切换到type mapKeys []*mapKey和map[*mapKey]string。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go