Go中interface != nil不一定不是nil

摘要:

interface{} 值 != nil不一定不是nil,应使用reflect库判断是否是nil。

测试示例:

// todo interface != nil 不一定 不是nil
var value map[string]interface{}
reqMap := make(map[string]interface{})
reqMap["key"] = value

value2, ok := reqMap["key"]
if ok {
	fmt.Print("ok = true\n")
} else {
	fmt.Printf("ok = false, value = %v\n", value2)
}

if ok {
	var convertValue map[string]interface{}
	var newMap map[string]interface{}
	convertValue = value2.(map[string]interface{})
	newMap["new"] = convertValue
	fmt.Print(convertValue)
}

断点调试
Go中interface != nil不一定不是nil_第1张图片
在进行到断点处时,会报错“assignment to entry in nil map”
在这里插入图片描述

我们不能对一个map的value赋值为nil,在此处如果仅通过判断interface{}是否为nil,此处可能导致误判,所以这里建议通过反射进行判断。

修改方法


// CodeExplore .
func CodeExplore(ctx context.Context) {
	logs.CtxInfo(ctx, "hello world")

	// todo interface != nil 不一定 不是nil
	var value map[string]interface{}
	reqMap := make(map[string]interface{})
	reqMap["key"] = value

	// 正确
	value3, _ := reqMap["key"]
	if !isNil(value3) {  // 判断结果为false
		var newMap map[string]interface{}
		newMap["new"] = value3
	}

	// 错误
	//value2, ok := reqMap["key"]
	//if ok {
	//	fmt.Print("ok = true\n")
	//} else {
	//	fmt.Printf("ok = false, value = %v\n", value2)
	//}
	//if ok {
	//	var convertValue map[string]interface{}
	//	var newMap map[string]interface{}
	//	convertValue = value2.(map[string]interface{})
	//	newMap["new"] = convertValue
	//	fmt.Print(convertValue)
	//}

	return
}

func isNil(val interface{}) bool {
	if val == nil {
		return true
	}

	v := reflect.ValueOf(val)
	k := v.Kind()
	switch k {
	case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.UnsafePointer, reflect.Interface, reflect.Slice:
		return v.IsNil()
	default:
		return false
	}
}

你可能感兴趣的:(Go,golang,开发语言,后端)