接口数据返回后,如何与预期结果进行比较~这次挑选出常见类型的进行代码讲解,各位宝子可以自己拿代码运行下
package main
import (
"log"
"reflect"
"strings"
)
// 判断obj是否在target中,target支持的类型arrary,slice,map
func Contain(obj interface{}, target interface{}) (bool, string) {
targetValue := reflect.ValueOf(target)
log.Println("targetValue is :", reflect.ValueOf(target))
log.Println("reflect.TypeOf(target).Kind() is :", reflect.TypeOf(target).Kind())
switch reflect.TypeOf(target).Kind() {
case reflect.Slice, reflect.Array:
for i := 0; i < targetValue.Len(); i++ {
if targetValue.Index(i).Interface() == obj {
return true, "匹配成功"
}
}
case reflect.Map:
if targetValue.MapIndex(reflect.ValueOf(obj)).IsValid() {
return true, "匹配成功"
}
}
return false, "不在预期结果内或者类型不匹配"
}
//string比对
func StringValueCompare(obj string, target string) (bool, string) {
if strings.Compare(obj, target) == 0 {
return true, "字符串匹配成功"
} else {
return false, "字符串不在预期结果内或者类型不匹配"
}
}
func main() {
//测试数据是array类型
a := 1
b := [3]int{1, 2, 3}
println(Contain(a, b))
c := "a"
d := [4]string{"a", "bb"}
println(Contain(c, d))
e := 1.1
f := [4]float64{1.2, 1.3, 1.1, 1.4}
println(Contain(e, f))
g := 1
h := [4]interface{}{2, 4, 6, 1}
println(Contain(g, h))
i := [4]int64{}
println(Contain(a, i))
//测试数据是slice类型
aa := 1
bb := []int{1, 2, 3}
println(Contain(aa, bb))
//测试数据是map类型
var aaa = map[int]string{1: "1", 2: "2"}
println(Contain(3, aaa))
println(Contain(1, aaa))
var cc = map[string]interface{}{"a": "1,2,3", "b": 2}
println(Contain("b", cc))
//测试数据是字符串
println(StringValueCompare("a", "a"))
println(StringValueCompare("a", "aa"))
}