如何在进行中反转切片? [英] How do I reverse a slice in go?

查看:40
本文介绍了如何在进行中反转切片?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I reverse an arbitrary slice ([]interface{}) in Go? I'd rather not have to write Less and Swap to use sort.Reverse. Is there a simple, builtin way to do this?

推荐答案

没有一个简单的内置函数可用于反转接口切片{}.您可以编写一个for循环来做到这一点:

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

使用Go 1.8中引入的 reflect.Swapper 函数编写通用的换向功能:

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

游乐场示例

这篇关于如何在进行中反转切片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆