Is there a way to iterate over a slice in reverse in Go?

后端 未结 7 1620
猫巷女王i
猫巷女王i 2021-01-30 15:28

It would be convenient to be able to say something like:

for _, element := reverse range mySlice {
        ...
}
7条回答
  •  旧巷少年郎
    2021-01-30 16:02

    I guess this is the easiest way to reverse arrays.:

    package main
    
    import "fmt"
    
    // how can we reverse write the array
    func main() {
    
        arr := [...]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
        revArr := [len(arr)]int{} // making empty array for write reverse
    
        for i := range arr {
            revArr[len(arr)-1-i] = arr[i]
        }
    
        fmt.Println(revArr)
    }
    

    https://play.golang.org/p/QQhj26-FhtF

提交回复
热议问题