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

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]
	}
}
reflect.Swapper
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)
	}

}

上面两个函数实现的效果一样

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

输出:

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 转摘请注明来源