Go语言中nil interface 和 nil interface 值对比测试及注意事项
Go  /  管理员 发布于 1年前   274
interface 看起来像指针类型,但它不是。
interface 类型的变量只有在类型和值均为 nil 时才为 nil
注意点1:
当 interface 变量的值是跟随其他变量变化的,与 nil 比较相等时
代码示例:
func main() {
var data *byte
var in interface{}
fmt.Println(data, data == nil) // <nil> true
fmt.Println(in, in == nil) // <nil> true
in = data
fmt.Println(in, in == nil) // <nil> false // data 值为 nil,但 in 值不为 nil
}
注意点2:
如果你的函数返回值类型是 interface,更要小心这个坑
代码示例:
// 错误示例
func main() {
doIt := func(arg int) interface{} {
var result *struct{} = nil
if arg > 0 {
result = &struct{}{}
}
return result
}
if res := doIt(-1); res != nil {
fmt.Println("Good result: ", res) // Good result: <nil>
fmt.Printf("%T\n", res) // *struct {} // res 不是 nil,它的值为 nil
fmt.Printf("%v\n", res) // <nil>
}
}
// 正确示例
func main() {
doIt := func(arg int) interface{} {
var result *struct{} = nil
if arg > 0 {
result = &struct{}{}
} else {
return nil // 明确指明返回 nil
}
return result
}
if res := doIt(-1); res != nil {
fmt.Println("Good result: ", res)
} else {
fmt.Println("Bad result: ", res) // Bad result: <nil>
}
}
更多go语言的注意点,请收藏本站网址:https://www.zongscan.com/
阿凡达123 在
golang 怎么做热更新中评论 也可以看看这个:https://github.com/edwingeng/hot..博主 在
hyperf框架常用命令-在centos7中退出命令及在docker容器中退出命令中评论 @路过的靓仔:cdn静态资源被墙,已修复..GGGGGGGGG 在
layui框架常用输入框介绍中评论 写的很好解决问题..路过的靓仔 在
hyperf框架常用命令-在centos7中退出命令及在docker容器中退出命令中评论 剩下好多 wait 状态的..激光豆芽 在
为什么你不能安逸?国内996为什么没有国外955香?中评论 国内现在无意义的内卷太多了..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号