当前位置:网站首页>面试官:值为 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")
}
}
边栏推荐
- VM11289 WAService. js:2 Do not have __ e handler in component:
- [combinatorics] recursive equation (definition of general solution | structure theorem of general solution of recursive equation without multiple roots)
- Vs2013 has blocked the installer, and ie10 needs to be installed
- Rsync remote synchronization
- 【RT-Thread】nxp rt10xx 设备驱动框架之--hwtimer搭建和使用
- 国内如何购买Google Colab会员
- Electronic technology 20th autumn "Introduction to machine manufacturing" online assignment 3 [standard answer]
- Leetcode 669 pruning binary search tree -- recursive method and iterative method
- AcWing 3438. 数制转换
- [combinatorics] recursive equation (special solution form | special solution solving method | special solution example)
猜你喜欢
![[RT thread] construction and use of --hwtimer of NXP rt10xx device driver framework](/img/df/a7719bcb00ff66e21f3a391ab94573.png)
[RT thread] construction and use of --hwtimer of NXP rt10xx device driver framework

Cloud primordial weekly | CNCF released the 2021 cloud primordial development status report, which was released on istio 1.13

TensorBoard快速入门(Pytorch使用TensorBoard)

Internet hospital his management platform source code, online consultation, appointment registration smart hospital applet source code

Test your trained model

Tensorboard quick start (pytoch uses tensorboard)

Swm32 series Tutorial 4 port mapping and serial port application

PS screen printing brush 131, many illustrators have followed suit

Simple use of unity pen XR grab

鸿蒙第三次培训
随机推荐
SWM32系列教程4-端口映射及串口应用
Leetcode 669 pruning binary search tree -- recursive method and iterative method
Automata and automatic line of non-standard design
September, 19, "cam principle and application" online assignment [Full Score answer]
Electronic Science and technology 20th autumn "Microcomputer Principle and application" online assignment 2 [standard answer]
[combinatorics] recursive equation (special solution form | special solution solving method | special solution example)
SVN如何查看修改的文件记录
Vs code plug-in korofileheader
Comparison of kotlin collaboration + retro build network request schemes
How do large consumer enterprises make digital transformation?
[set theory] order relation: summary (partial order relation | partial order set | comparable | strictly less than | covering | hasto | total order relation | quasi order relation | partial order rela
[RT thread] NXP rt10xx device driver framework -- RTC construction and use
Great changes! National housing prices fell below the 10000 yuan mark
Life is still confused? Maybe these subscription numbers have the answers you need!
vs2013已阻止安装程序,需安装IE10
Play with fancy special effects. This AE super kit is for you
HP 阵列卡排障一例
Simple configuration of postfix server
Where is the monitoring page of RDS database?
PR second time