-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathmain.go
126 lines (105 loc) · 2.63 KB
/
main.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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package main
import (
"errors"
"fmt"
)
/* 闭包应用
闭包经常用于回调函数,当IO操作(例如从网络获取数据、文件读写)完成的时候,会对获取的数据进行某些操作,这些操作可以交给函数对象处理
*/
// Traveser 定义函数类型 用于排序
type Traveser func(ele interface{})
// SortByDescending 具体操作:降序排序数组元素
func SortByDescending(ele interface{}) {
intSlice, ok := ele.([]int)
if !ok {
return
}
length := len(intSlice)
for i := 0; i < length-1; i++ {
isChange := false
for j := 0; j < length-1-i; j++ {
if intSlice[j] < intSlice[j+1] {
isChange = true
intSlice[j], intSlice[j+1] = intSlice[j+1], intSlice[j]
}
}
if isChange == false {
return
}
}
}
// SortByAscending具体操作:升序排序数组元素
func SortByAscending(ele interface{}) {
intSlice, ok := ele.([]int)
if !ok {
return
}
length := len(intSlice)
for i := 0; i < length-1; i++ {
isChange := false
for j := 0; j < length-1-i; j++ {
if intSlice[j] > intSlice[j+1] {
isChange = true
intSlice[j], intSlice[j+1] = intSlice[j+1], intSlice[j]
}
}
if isChange == false {
return
}
}
}
func process(array interface{}, traveser Traveser) error {
if array == nil {
return errors.New("nil pointer")
}
var length int // 定义数组长度
switch array.(type) {
case []int:
length = len(array.([]int))
case []string:
length = len(array.([]string))
case []float32:
length = len(array.([]float32))
default:
return errors.New("error type")
}
if length == 0 {
return errors.New("len is zero")
}
traveser(array)
return nil
}
//在一些公共的操作中经常会包含一些差异性的特殊操作,而这些差异性的操作可以用函数来进行封装。
func main() {
// 1. int类型切片
intSlice := []int{3, 1, 4, 2}
process(intSlice, SortByDescending)
fmt.Println(intSlice) //[4 3 2 1]
process(intSlice, SortByAscending)
fmt.Println(intSlice) //[1 2 3 4]
// 2. string类型切片
stringSlice := []string{"hello", "world", "china"}
/*
具体操作:使用匿名函数封装输出操作
*/
process(stringSlice, func(elem interface{}) {
if slice, ok := elem.([]string); ok {
for index, value := range slice {
fmt.Println("index:", index, " value:", value)
}
}
})
// 3. float32类型切片
floatSlice := []float32{1.2, 3.4, 2.4}
/*
具体操作:使用匿名函数封装自定义操作
*/
process(floatSlice, func(elem interface{}) {
if slice, ok := elem.([]float32); ok {
for index, value := range slice {
slice[index] = value * 2
}
}
})
fmt.Println(floatSlice) //[2.4 6.8 4.8]
}