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

后端 未结 7 1616
猫巷女王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 15:56

    When I need to extract elements from a slice and reverse range, I use something like this code:

    // reverse range
    // Go Playground: https://play.golang.org/p/gx6fJIfb7fo
    package main
    
    import (
        "fmt"
    )
    
    type Elem struct {
        Id   int64
        Name string
    }
    
    type Elems []Elem
    
    func main() {
        mySlice := Elems{{Id: 0, Name: "Alice"}, {Id: 1, Name: "Bob"}, {Id: 2, Name: "Carol"}}
        for i, element := range mySlice {
            fmt.Printf("Normal  range: [%v] %+v\n", i, element)
        }
    
        //mySlice = Elems{}
        //mySlice = Elems{{Id: 0, Name: "Alice"}}
        if last := len(mySlice) - 1; last >= 0 {
            for i, element := last, mySlice[0]; i >= 0; i-- {
                element = mySlice[i]
                fmt.Printf("Reverse range: [%v] %+v\n", i, element)
            }
        } else {
            fmt.Println("mySlice empty")
        }
    }
    

    Output:

    Normal  range: [0] {Id:0 Name:Alice}
    Normal  range: [1] {Id:1 Name:Bob}
    Normal  range: [2] {Id:2 Name:Carol}
    Reverse range: [2] {Id:2 Name:Carol}
    Reverse range: [1] {Id:1 Name:Bob}
    Reverse range: [0] {Id:0 Name:Alice}
    

    Playground: https://play.golang.org/p/gx6fJIfb7fo

提交回复
热议问题