How do I reverse a slice in go?

前端 未结 3 1836
野性不改
野性不改 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:54

    This will return a reversed slice without modifying the original slice.

    Algorithm used from official wiki page: 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
    }
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-10 04:57

    There are my code example, you can run it in 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)
    }
    
    
    0 讨论(0)
提交回复
热议问题