在Go语言中,有没有一种方法可以反向迭代一个切片?

qc6wkl3g  于 2022-12-31  发布在  Go
关注(0)|答案(8)|浏览(170)

如果能说这样的话,那就方便了:

for _, element := reverse range mySlice {
        ...
}
sd2nnvve

sd2nnvve1#

不,没有方便的运算符可以将它添加到范围1中,你必须做一个普通的for循环倒计时:

s := []int{5, 4, 3, 2, 1}
for i := len(s)-1; i >= 0; i-- {
   fmt.Println(s[i])
}
flvlnr44

flvlnr442#

您还可以执行以下操作:

s := []int{5, 4, 3, 2, 1}
for i := range s {
        fmt.Println(s[len(s)-1-i]) // Suggestion: do `last := len(s)-1` before the loop
}

输出:

1
2
3
4
5

也在这里:http://play.golang.org/p/l7Z69TV7Vl

vlf7wbxs

vlf7wbxs3#

指数变化

for k := range s {
        k = len(s) - 1 - k
        // now k starts from the end
    }
gywdnpxw

gywdnpxw4#

如何使用defer:

s := []int{5, 4, 3, 2, 1}
for i, _ := range s {
   defer fmt.Println(s[i])
}
bprjcwpo

bprjcwpo5#

你可以使用一个通道来反转函数中的列表,而不需要复制它。在我看来,这会使代码更好。

package main

import (
    "fmt"
)

func reverse(lst []string) chan string {
    ret := make(chan string)
    go func() {
        for i, _ := range lst {
            ret <- lst[len(lst)-1-i]
        }
        close(ret)
    }()
    return ret
}

func main() {
    elms := []string{"a", "b", "c", "d"}
    for e := range reverse(elms) {
        fmt.Println(e)
    }
}
yzckvree

yzckvree6#

在2022年,你可以使用泛型来反转任何切片:

func reverse[S ~[]E, E any](s S) {
    for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
        s[i], s[j] = s[j], s[i]
    }
}
qojgxg4l

qojgxg4l7#

当我需要从一个切片中提取元素并反转范围时,我使用了类似于下面的代码:

// 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")
    }
}

输出:

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

ylamdve6

ylamdve68#

可以使用go-funk中的funk.ForEachRight方法:

results := []int{}

funk.ForEachRight([]int{1, 2, 3, 4}, func(x int) {
    results = append(results, x)
})

fmt.Println(results) // []int{4, 3, 2, 1}

相关问题