How do I reverse a slice in go?

前端 未结 3 1842
野性不改
野性不改 2020-12-10 04:37

How do I reverse an arbitrary slice ([]interface{}) in Go? I\'d rather not have to write Less and Swap to use sort.Reverse

3条回答
  •  醉话见心
    2020-12-10 04:56

    There is not a simple, built-in for reversing a slice of interface{}. You can write a for loop to do it:

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

    Use the reflect.Swapper function introduced in Go 1.8 to write a generic reversing function:

    func reverseAny(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)
        }
    }
    

    playground example

提交回复
热议问题