示例#1
0
文件: slice.go 项目: xgfone/go-tools
// Return true if value is in slice. Or false. Also reutrn false if value or
// slice is nil, or the length of slice is 0.
//
// The type of value must be consistent with the type of the element of slice.
// Or panic. If the type is the customizable struct, it MUST implement the interface
// Comparer in the package "github.com/xgfone/go-tools/compare".
func In(value interface{}, slice interface{}) bool {
	if value == nil || slice == nil {
		return false
	}

	stype := reflect.ValueOf(slice)
	if stype.Kind() == reflect.Ptr {
		stype = stype.Elem()
	}

	if stype.Kind() != reflect.Array && stype.Kind() != reflect.Slice {
		panic("The second argument is not a slice or an array")
	}

	slen := stype.Len()
	if slen == 0 {
		return false
	}

	vv := reflect.ValueOf(value)
	if stype.Index(0).Kind() != reflect.ValueOf(value).Kind() {
		panic("The type of value must be consistent with the type of the element of slice")
	}

	for i := 0; i < slen; i++ {
		v1 := vv.Interface()
		v2 := stype.Index(i).Interface()
		if compare.EQ(v1, v2) {
			return true
		}
	}

	return false
}
示例#2
0
func TestCompare(t *testing.T) {
	v1 := []uint16{1, 2, 4}
	v2 := []uint16{1, 2, 3}
	if !compare.GT(v1, v2) {
		t.Fail()
	}

	if !compare.LT(v2, v1) {
		t.Fail()
	}

	if compare.EQ(v1, v2) {
		t.Fail()
	}

	if !compare.EQ([]int{1, 2, 3}, []int{1, 2, 3}) {
		t.Fail()
	}

	if compare.LT([]int{1, 2, 3}, []int{1, 2, 3}) {
		t.Fail()
	}
}