增加in array能力
This commit is contained in:
parent
c886ff6b20
commit
6cee12a850
50
array.go
Normal file
50
array.go
Normal file
@ -0,0 +1,50 @@
|
||||
// Package util ...
|
||||
//
|
||||
// Description : util ...
|
||||
//
|
||||
// Author : go_developer@163.com<白茶清欢>
|
||||
//
|
||||
// Date : 2023-03-30 14:35
|
||||
package util
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
)
|
||||
|
||||
type array struct {
|
||||
}
|
||||
|
||||
// In 判断指定数据是否在目标数据集中, 不存在返回 -1 , 存在时返回数据对应的索引
|
||||
//
|
||||
// Author : go_developer@163.com<白茶清欢>
|
||||
//
|
||||
// Date : 14:38 2023/3/30
|
||||
func (a *array) In(search interface{}, source interface{}) int {
|
||||
if nil == source {
|
||||
return -1
|
||||
}
|
||||
list, ok := source.([]interface{})
|
||||
if !ok {
|
||||
return -1
|
||||
}
|
||||
if nil == search {
|
||||
for idx, item := range list {
|
||||
if item == nil {
|
||||
return idx
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
searchType := reflect.TypeOf(search).Kind()
|
||||
for idx, item := range list {
|
||||
if searchType != reflect.TypeOf(item).Kind() {
|
||||
// 类型不同
|
||||
continue
|
||||
}
|
||||
if fmt.Sprintf("%v", search) == fmt.Sprintf("%v", item) {
|
||||
return idx
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
20
array_test.go
Normal file
20
array_test.go
Normal file
@ -0,0 +1,20 @@
|
||||
// Package util ...
|
||||
//
|
||||
// Description : util ...
|
||||
//
|
||||
// Author : go_developer@163.com<白茶清欢>
|
||||
//
|
||||
// Date : 2023-03-30 14:43
|
||||
package util
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func Test_array_In(t *testing.T) {
|
||||
fmt.Println(Array.In(1234, []string{"1234", "123", "1"}))
|
||||
fmt.Println(Array.In(1234, []interface{}{1234, "123", "1"}))
|
||||
fmt.Println(Array.In(nil, []interface{}{1234, "123", "1"}))
|
||||
fmt.Println(Array.In(nil, []interface{}{1234, "123", "1", nil}))
|
||||
}
|
Loading…
Reference in New Issue
Block a user