当前位置:网站首页>面试官:值为 nil 为什么不等于 nil ?
面试官:值为 nil 为什么不等于 nil ?
2022-07-03 17:32:00 【小锟哥哥】

小明同学去面试被问到了这么一个面试题,请看代码:
var f func()
var a *struct{}
list := []interface{}{f, a}
for _, item := range list {
if item == nil {
fmt.Println("nil")
}
}
请问输出结果是啥?
可能很多同学,会认为结果是输出两个 nil。
为什么呢?
因为 f 和 a 都没初始化,都是 nil,所以循环遍历后肯定也是 nil。
如果你的答案也是这样,那就掉进坑里了。
答案是,啥都不会输出!
且听我慢慢给你分析:
一、变量的值和类型
我们先来打印下这两个值:
var f func()
var a *struct{}
fmt.Println(f, a)
// 输出结果
<nil> <nil>
我们这样打印其实是打印的是他的值,是 nil 没错的。
但是类型不是 nil。
我们可以这样打印他类型:
var f func()
var a *struct{}
fmt.Printf("%T,%T \n", f, a)
// 输出结果
func(),*struct {}
二、if 判 nil 含有对类型的判断
当我们从 interface 里面把对象取出来后,使用 if 进行判断,他不单单的比较的是值,还有类型。
看下这段代码:
var f func()
var a *struct{}
list := []interface{}{f, a, nil}
for _, item := range list {
fmt.Println("item=", item)
fmt.Printf("item type: %T \n", item)
if item == nil {
fmt.Println("item == nil")
}
fmt.Println("----")
}
}
现在看下运行结果:
$ go run main.go
item= <nil>
item type: func()
----
item= <nil>
item type: *struct {}
----
item= <nil>
item type: <nil>
item == nil
----
你会发现之后最后 nil 的判断是通过的,前面两个判断都不通过。
三、怎么判断值是否为 nil
我们在写代码时,最好是尽量避免这种代码,如果硬要这么写,那我们可以通过以下两种常见方式判 nil。
1、断言
list := []interface{}{f, a}
for _, item := range list {
if v, ok := item.(func()); ok && v == nil {
fmt.Println("item is nil")
}
if v, ok := item.(*struct{}); ok && v == nil {
fmt.Println("item is nil")
}
}
2、反射
list := []interface{}{f, a}
for _, item := range list {
if reflect.ValueOf(item).IsNil() {
fmt.Println("item is nil")
}
}
边栏推荐
- Analyse ArrayList 3: suppression d'éléments
- Rsync remote synchronization
- Leetcode Valentine's Day Special - looking for a single dog
- 企业级自定义表单引擎解决方案(十一)--表单规则引擎1
- 【RT-Thread】nxp rt10xx 设备驱动框架之--Pin搭建和使用
- [RT thread] NXP rt10xx device driver framework -- Audio construction and use
- VM11289 WAService. js:2 Do not have __ e handler in component:
- TensorBoard快速入门(Pytorch使用TensorBoard)
- How to purchase Google colab members in China
- 一位普通程序员一天工作清单
猜你喜欢

Play with fancy special effects. This AE super kit is for you
![How to read the source code [debug and observe the source code]](/img/40/a2fca67bcde3c468a739c6990325f4.jpg)
How to read the source code [debug and observe the source code]

国内如何购买Google Colab会员
![[RT thread] NXP rt10xx device driver framework -- Audio construction and use](/img/85/32a83eaa4b7f5b30d4d7c4f4c32791.png)
[RT thread] NXP rt10xx device driver framework -- Audio construction and use

TensorBoard快速入门(Pytorch使用TensorBoard)

How do large consumer enterprises make digital transformation?

QT学习日记9——对话框

1164 Good in C

新库上线 | CnOpenData中国保险机构网点全集数据

Design e-commerce spike
随机推荐
简单配置PostFix服务器
STM32H7 HAL库SPI DMA发送一直处于busy的解决办法
Unity notes unityxr simple to use
远程办公工具分享|社区征文
Web-ui automated testing - the most complete element positioning method
Wechat applet for the first time
Internet Hospital his Management Platform source, online Inquiry, appointment Registration Smart Hospital Small program source
Y is always discrete and can't understand, how to solve it? Answer: read it several times
Kotlin learning quick start (7) -- wonderful use of expansion
国内如何购买Google Colab会员
Cloud primordial weekly | CNCF released the 2021 cloud primordial development status report, which was released on istio 1.13
Leetcode 108 converts an ordered array into a binary search tree -- recursive method
September, 19, "cam principle and application" online assignment [Full Score answer]
[RT thread] NXP rt10xx device driver framework -- pin construction and use
i++与++i的区别:通俗易懂的讲述他们的区别
一位普通程序员一天工作清单
Collection of the most beautiful graduation photos in the graduation season, collection of excellent graduation photos
Is AI too slow to design pictures and draw illustrations? 3 sets of practical brushes to save you
AcWing 3438. 数制转换
Swm32 series Tutorial 4 port mapping and serial port application