Go语言中nil interface 和 nil interface 值对比测试及注意事项
Go  /  管理员 发布于 1年前   477
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/
博主 在
2023年国务院办公厅春节放假通知:1月21日起休7天中评论 @ xiaoB 你只管努力,剩下的叫给天意;天若有情天亦老,..xiaoB 在
2023年国务院办公厅春节放假通知:1月21日起休7天中评论 会不会春节放假后又阳一次?..BUG4 在
你翻墙过吗?国内使用vpn翻墙可能会被网警抓,你需了解的事中评论 不是吧?..博主 在
go语言+beego框架中获取get,post请求的所有参数中评论 @ t1 直接在router.go文件中配就ok..Jade 在
如何在MySQL查询中获得当月记录中评论 Dear zongscan.com team, We can skyroc..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号