Documentation
¶
Overview ¶
Package sliceutil 提供对数组和切片的相关功能
Index ¶
- func Contains(container, sub interface{}, eq func(i, j int) bool) bool
- func Count(slice interface{}, eq func(i int) bool) (count int)
- func Delete(slice interface{}, eq func(i int) bool) (size int)
- func Dup(slice interface{}, eq func(i, j int) bool) (indexes []int)
- func Index(slice interface{}, eq func(i int) bool) (index int)
- func QuickDelete(slice interface{}, eq func(i int) bool) (size int)
- func Reverse(slice interface{})
- func Unique(slice interface{}, eq func(i, j int) bool) (size int)
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Contains ¶ added in v0.4.0
Contains container 是否包含了 sub 中的所有元素
container 与 sub 都必须是数组或是切片类型。 如果只是需要判断某一个值是否在 container 中,可以使用 Count() 函数。 eq 用于判断两个数组或是切的某个元素是否相等,其原型为:
func(i, j int) bool
i 表示 container 的第 i 个元素,j 表示 sub 的第 j 个元素,两者顺序不能乱。
Example ¶
ints := []int{1, 2, 3, 4, 5} uints := []uint{1, 5, 2} fmt.Println(Contains(ints, uints, func(i, j int) bool { return uint(ints[i]) == uints[j] }))
Output: true
func Count ¶
Count 检测数组中指定值的数量
slice 需要检测的数组或是切片,其它类型会 panic; eq 对比函数,i 表示数组的下标,需要在函数将该下标表示的值与你需要的值进行比较是否相等;
Example ¶
intSlice := []int{1, 2, 3, 7, 0, 4, 7} fmt.Println(Count(intSlice, func(i int) bool { return intSlice[i] == 7 }))
Output: 2
func Delete ¶ added in v0.2.0
Delete 删除 slice 中符合 eq 条件的元素
slice 的类型只能是切片或是切片指针,其它任意类型都将 panic,数组也不行; eq 对比函数,用于确定指定的元素是否可以删除,返回 true 表示可以删除; size 返回新的数组大小,用户可以从原始数组上生成新的数组:
slice[:size]
Example ¶
intSlice := []int{1, 2, 3, 7, 0, 4, 7} size := Delete(intSlice, func(i int) bool { return intSlice[i] == 7 }) fmt.Println("Delete:", intSlice[:size]) intSlice = []int{1, 2, 3, 7, 0, 4, 7} size = QuickDelete(intSlice, func(i int) bool { return intSlice[i] == 7 || intSlice[i] == 2 }) fmt.Println("QuickDelete:", intSlice[:size])
Output: Delete: [1 2 3 0 4] QuickDelete: [1 4 3 0]
func Dup ¶
Dup 检测数组或是切片中是否包含重复的值
slice 需要检测的数组或是切片,其它类型会 panic; eq 对比数组中两个值是否相等,相等需要返回 true; 在存在相同元素时,会返回该相同元素的下标列表, 当有多组相同元素时,仅返回第一组相同元素的下标。
Example ¶
intSlice := []int{1, 2, 3, 7, 0, 4, 7} fmt.Println(Dup(intSlice, func(i, j int) bool { return intSlice[i] == intSlice[j] }))
Output: [3 6]
func Index ¶ added in v0.7.0
Index 从 slice 查找符合 eq 的第一个元素并返回其在数组中的元素
Example ¶
intSlice := []int{1, 2, 3, 7, 0, 4, 7} fmt.Println(Index(intSlice, func(i int) bool { return intSlice[i] == 7 }))
Output: 3
func QuickDelete ¶ added in v0.2.0
QuickDelete 删除 slice 中符合 eq 条件的元素
功能与 Delete 相同,但是性能相对 Delete 会好一些,同时也不再保证元素顺序与原数组相同。
Types ¶
This section is empty.