如何在 go 中反转切片?

How do I reverse a slice in go?

如何在 Go 中反转任意切片 ([]interface{})?我宁愿不必写 LessSwap 来使用 sort.Reverse。有没有简单的内置方法来做到这一点?

标准库没有用于反转切片的内置函数。使用 for 循环反转切片:

for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
    s[i], s[j] = s[j], s[i]
}

在 Go 1.18 或更高版本中使用类型参数编写通用反向函数:

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]
    }
}

使用reflect.Swapper在Go 1.8或更高版本中编写一个适用于任意切片类型的函数:

func reverse(s interface{}) {
    n := reflect.ValueOf(s).Len()
    swap := reflect.Swapper(s)
    for i, j := 0, n-1; i < j; i, j = i+1, j-1 {
        swap(i, j)
    }
}

Run the code on the Go playground.

此答案中的函数就地反转切片。如果不想修改原切片,copy the slice再反转切片。

有我的代码示例,你可以运行在playground

package main

import (
    "fmt"
    "reflect"
    "errors"
)

func ReverseSlice(data interface{}) {
    value := reflect.ValueOf(data)
    if value.Kind() != reflect.Slice {
        panic(errors.New("data must be a slice type"))
    }
    valueLen := value.Len()
    for i := 0; i <= int((valueLen-1)/2); i++ {
        reverseIndex := valueLen - 1 - i
        tmp := value.Index(reverseIndex).Interface()
        value.Index(reverseIndex).Set(value.Index(i))
        value.Index(i).Set(reflect.ValueOf(tmp))
    }
}


func main() {
    names := []string{"bob", "mary", "sally", "michael"}
    ReverseSlice(names)
    fmt.Println(names)
}

这将 return 反转切片而不修改原始切片。

官方维基页面使用的算法:https://github.com/golang/go/wiki/SliceTricks#reversing

func reverse(s []interface{}) []interface{} {
    a := make([]interface{}, len(s))
    copy(a, s)

    for i := len(a)/2 - 1; i >= 0; i-- {
        opp := len(a) - 1 - i
        a[i], a[opp] = a[opp], a[i]
    }

    return a
}

这是我在 generics 中使用的函数(转到 1.18+)。您可以使用它来反转任何类型的切片甚至字符串(使用 split/join 技巧)。它不会改变原始切片。

package main

import (
    "fmt"
    "strings"
)

func Reverse[T any](original []T) (reversed []T) {
    reversed = make([]T, len(original))
    copy(reversed, original)

    for i := len(reversed)/2 - 1; i >= 0; i-- {
        tmp := len(reversed) - 1 - i
        reversed[i], reversed[tmp] = reversed[tmp], reversed[i]
    }

    return
}

func main() {
    a := []string{"a", "b", "c"}
    fmt.Println(a, Reverse(a))

    b := []uint{0, 1, 2}
    fmt.Println(b, Reverse(b))

    c := "abc"
    fmt.Println(c, strings.Join(Reverse(strings.Split(c, "")), ""))
}

Better Go Playground

这是另一种可能的反转通用切片的方法(转到 1.18)

// You can edit this code!
// Click here and start typing.
package main

import (
    "fmt"
    "sort"
)

func main() {
    nums := []int64{10, 5, 15, 20, 1, 100, -1}
    ReverseSlice(nums)
    fmt.Println(nums)

    strs := []string{"hello", "world"}
    ReverseSlice(strs)
    fmt.Println(strs)

    runes := []rune{'h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd'}
    ReverseSlice(runes)
    for _, r := range runes {
        fmt.Print(string(r), " ")
    }
}

func ReverseSlice[T comparable](s []T) {
    sort.SliceStable(s, func(i, j int) bool {
        return i > j
    })
}

运行 上面的程序应该输出:

[-1 100 1 20 15 5 10]
[world hello]
d l r o w o l l e h 
Program exited.