GolangNote

Golang笔记

Golang 倒转任意数组 slice

Permalink

使用遍历的方式把一个任意类型的数组倒转。

Go: reverse
1
2
3
4
5
func reverse(s []interface{}) {
	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 函数来帮忙

Go: reverseAny
1
2
3
4
5
6
7
8
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: 数组倒转
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package main

import (
	"fmt"
	"reflect"
)

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

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

}

func main() {
	s := []interface{}{1, "2", "中文", uint(3), byte(4), "a", float64(5)}
	fmt.Println(s)
	reverse(s)
	fmt.Println(s)
	reverseAny(s)
	fmt.Println(s)
}

输出:

Bash:
1
2
3
[1 2 中文 3 4 a 5]
[5 a 4 3 中文 2 1]
[1 2 中文 3 4 a 5]

本文网址: https://golangnote.com/topic/283.html 转摘请注明来源

Related articles

Golang http client 处理重定向网页

假设一个网址有多个重定向,A-B-C-D,使用 http.Client.Get 最后取得的内容是网址D的内容,我们该手动处理包含重定向的网址。...

Golang quicktemplate 模版快速入门

Golang 有很多的模版引擎,自带的 `html/template` 也很好,大多数情况都能满足需求,只是有些逻辑、条件判断不好在模版里实现, `quicktemplate` 是个很好的选择。...

Write a Comment to "Golang 倒转任意数组 slice"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.20 Processed in 0ms