-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathslice.go
63 lines (56 loc) · 1.06 KB
/
slice.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
package lib
func InSlice[T comparable](element T, Slice []T) bool {
for _, v := range Slice {
if element == v {
return true
}
}
return false
}
func Unique[T comparable](slice []T) []T {
// 创建一个临时map用来存储数组元素
temp := make(map[T]struct{})
index := 0
// 将元素放入map中
for _, v := range slice {
temp[v] = struct{}{}
}
tempSlice := make([]T, len(temp))
for key := range temp {
tempSlice[index] = key
index++
}
return tempSlice
}
func Push[T any](slice []T, element T) []T {
slice = append(slice, element)
return slice
}
func Pop[T any](slice []T) []T {
if len(slice) > 0 {
slice = slice[:len(slice)-1]
}
return slice
}
func PopFront[T any](slice []T) []T {
if len(slice) > 0 {
slice = slice[1:]
}
return slice
}
func Exclude[T comparable](slice []T, element T) []T {
result := slice[:0]
for _, v := range slice {
if v != element {
result = append(result, v)
}
}
return result
}
func Reverse[T any](s []T) []T {
h := make([]T, len(s))
for i := 0; i < len(s); i++ {
h[i] = s[len(s)-i-1]
}
return h
}