package Tools
import "sort"
//对[]string 类型的切片进行元素唯一化处理,返回来的元素已经排好序
func SetString(arr []string) []string {
newArr := make([]string, 0)
for i := 0; i < len(arr); i++ {
repeat := false
for j := i + 1; j < len(arr); j++ {
if arr[i] == arr[j] {
repeat = true
}
}
if !repeat {
newArr = append(newArr, arr[i])
}
}
sort.Strings(newArr)
return (newArr)
}
//对[]int 类型的切片进行元素唯一化处理,返回来的元素已经排好序
func SetInt(arr []int) []int {
newArr := make([]int, 0)
for i := 0; i < len(arr); i++ {
repeat := false
for j := i + 1; j < len(arr); j++ {
if arr[i] == arr[j] {
repeat = true
}
}
if !repeat {
newArr = append(newArr, arr[i])
}
}
sort.Ints(newArr)
return (newArr)
}
//c := []interface{}{1,2,3,3,4,4}
// d := Tools.Set(c) //[1 2 3 4]
//注意场景切片时的语法 c := interface{}{1,1,2,2,3,3,4,5}
func Set(arr []interface{}) []interface{} {
newArr := make([]interface{}, 0)
for i := 0; i < len(arr); i++ {
repeat := false
for j := i + 1; j < len(arr); j++ {
if arr[i] == arr[j] {
repeat = true
}
}
if !repeat {
newArr = append(newArr, arr[i])
}
}
return (newArr)
}
SetString( []string ) []string 针对 []string,
SetInt( []int ) 针对 []int ,
Set([]interface{}) []interface{} 针对 []interface{}
func main() {
a := []string{"a","b","a","c","a","b"}
b := Tools.SetString(a)
fmt.Println(b)
c := []interface{}{1,2,3,3,4,4}
d := Tools.Set(c) //[1 2 3 4]
fmt.Println(d)
输出结果为
[a b c]
[1 2 3 4]
Process finished with exit code 0
有疑问加站长微信联系(非本文作者)