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

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

问题描述

如何在 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 built-in function or a function in the standard library for reversing a slice. Use a for loop to reverse a slice:

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 函数编写通用的反转函数:>

Use the reflect.Swapper function 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)
    }
}

在 Go playground 上运行代码.

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

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