切片迭代顺序 [英] slice iteration order in go

查看:80
本文介绍了切片迭代顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我认为这可能是一个老问题,但是我在stackoverflow上没有发现任何东西.在go中,不保证地图上的迭代顺序是可重现的.因此,建议的方法是将键保留在一个切片中并对该切片进行排序.然后在该切片上进行迭代以从映射中检索值,以便我们按顺序获取它们(因为由键组成的切片已排序,因此将以可重现的顺序排列).因此,这意味着需要对切片进行排序,否则对切片的迭代也不会给出可重现的顺序.但是,当我在操场上尝试下面的代码时,我总是发现迭代中保持了顺序,然后在地图迭代的情况下,为什么需要对键片进行排序?

Ok, i think this may be an old question, but i didn't find anything over the stackoverflow. In go , the iteration order over a map is not guranteed to be reproducible. So, the way suggest is to hold the keys in a slice and sort that slice. Then iterate over that slice to retrieve the values from the map, so that we get them in order(since slice composed of keys is sorted, so will be in reproducible order). So this goes to imply that the slice need be sorted else iteration over the slice will also not give reproducible order. But when i tried the below code in playground, i always found the order maintained in iteration, then in the map iteration case, why the slice of keys need to be sorted?

func main() {
    var mySlice = make([]string, 0)
    mySlice = append(mySlice, "abcd")
    mySlice = append(mySlice, "efgh")
    mySlice = append(mySlice, "ijkl")
    mySlice = append(mySlice, "mnop")
    mySlice = append(mySlice, "qrst")
    mySlice = append(mySlice, "uvwxyz")
    for _, val := range mySlice {
        fmt.Println(val)
    }
    fmt.Println(strings.Join(mySlice, "|"))

}

输出:

abcd
efgh
ijkl
mnop
qrst
uvwxyz
abcd|efgh|ijkl|mnop|qrst|uvwxyz

推荐答案

对分片进行排序的唯一原因是因为您要按已排序的顺序附加项目.如果您按这样的未排序顺序附加项目

The only reason your slice is sorted is because you're appending items in already sorted order. If you appended items in an unsorted order like this

var mySlice = make([]string, 0)
mySlice = append(mySlice, "mnop")
mySlice = append(mySlice, "efgh")
mySlice = append(mySlice, "uvwxyz")
mySlice = append(mySlice, "ijkl")
mySlice = append(mySlice, "abcd")
mySlice = append(mySlice, "qrst")

(或通过从映射中拉键填充切片,这将是未排序的),则迭代的顺序将是未排序的(一致,是,但始终未排序).因此,如果您的目标是使用切片按排序顺序从地图中提取项目,则需要首先对切片进行排序,除非可以保证切片项目已按已排序的顺序插入.

(or populated a slice by pulling keys from a map, which would be unsorted), then the order on iteration would be unsorted (consistent, yes, but consistently unsorted). So, if your objective is to use the slice to pull items from a map in sorted order, then you need to first sort the slice, unless you can guarantee the slice items were inserted in an already sorted order.

这篇关于切片迭代顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆