golang nil interface 接口接收nil返回值的坑

参考文章:https://www.jianshu.com/p/111312188316

nil interface 和 nil interface 的值。
虽然 interface 看起来像指针类型,但它不是。
interface 类型的变量只有在类型和值均为 nil 时才为 nil

其实接口不是指针,内部存储的有实际imp的类型和val 两个值,本文的bug,返回的是nil (imp的值nil),但是它赋值给的是 接口的值,接口记录了它的实际类型type=*struct{}, val = nil 。

如果你的 interface 变量的值是跟随其他变量变化的,与 nil 比较相等时小心:

func main() {
	doIt := func(arg int) interface{} {
		var result *struct{} = nil
		if arg > 0 {
			result = &struct{}{}
		}
		return result
	}

	res := doIt(-1)
	if res != nil {
		fmt.Println("res is not nil, res = ", res)
	} else {
		fmt.Println("res is nil, res = ", res)
	}

	fmt.Println("Good result: ", res) // Good result:  
	fmt.Printf("%T\n", res)           // *struct {}   // res 不是 nil,它的值为 nil
	fmt.Printf("%v\n", res)           // 
}

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