可以这样说会很方便:
for _, element := reverse range mySlice {
...
}
不,没有方便的运算符可以将其添加到范围一中。你必须做一个正常的 for 循环倒计时:
s := []int{5, 4, 3, 2, 1}
for i := len(s)-1; i >= 0; i-- {
fmt.Println(s[i])
}
你也可以这样做:
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
随指数变化
for k := range s {
k = len(s) - 1 - k
// now k starts from the end
}
如何使用延迟:
s := []int{5, 4, 3, 2, 1}
for i, _ := range s {
defer fmt.Println(s[i])
}
可以使用通道来反转函数中的列表,而无需复制它。在我看来,它使代码更好。
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)
}
}
我想这是反转数组的最简单方法。:
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)
}
当我需要从切片和反向范围中提取元素时,我使用如下代码:
// 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}
游乐场: https: //play.golang.org/p/gx6fJIfb7fo
一个优雅的方法reverse range
:
如果您的切片是瞬态的:在元素数量大于零时循环,使用最后一个元素,然后将其删除。处理完第一个元素后,切片将为空:
s := []int{1, 2, 3, 4}
for len(s) > 0 {
item := s[len(s)-1]
fmt.Printf("Reverse item: %+v\n", item)
s = s[:len(s)-1]
}
输出:
Reverse item: 4
Reverse item: 3
Reverse item: 2
Reverse item: 1
去游乐场: https: //play.golang.org/p/XKB43k7M9j3
您可以使用go-funkfunk.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}