当前位置:网站首页>面试官:值为 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")
}
}
边栏推荐
- [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
- An example of HP array card troubleshooting
- Kotlin学习快速入门(7)——扩展的妙用
- 新库上线 | CnOpenData中国观鸟记录数据
- Hongmeng third training
- [RT thread] NXP rt10xx device driver framework -- RTC construction and use
- [RT thread] construction and use of --hwtimer of NXP rt10xx device driver framework
- Rsync remote synchronization
- [error reporting] omp: error 15: initializing libiomp5md dll, but found libiomp5md. dll already initialized.
- AcWing 4489. 最长子序列
猜你喜欢
鸿蒙第三次培训
[UE4] brush Arctic pack high quality Arctic terrain pack
1164 Good in C
How to read the source code [debug and observe the source code]
Luogu: p2685 [tjoi2012] Bridge
PS screen printing brush 131, many illustrators have followed suit
TensorBoard快速入门(Pytorch使用TensorBoard)
SWM32系列教程4-端口映射及串口应用
Life is still confused? Maybe these subscription numbers have the answers you need!
POM in idea XML graying solution
随机推荐
Online assignment 3 of mobile Internet technology in the 20th autumn of electronic technology [standard answer]
kubernetes资源对象介绍及常用命令(三)
1164 Good in C
A day's work list of an ordinary programmer
远程办公工具分享|社区征文
Analyse ArrayList 3: suppression d'éléments
SQL injection database operation foundation
Qt调节Win屏幕亮度和声音大小
Kubernetes resource object introduction and common commands (4)
Automata and automatic line of non-standard design
[mathematical logic] equivalent calculus and reasoning calculus of predicate logic (individual word | predicate | quantifier | predicate logic formula | two basic formulas | proposition symbolization
QT学习日记9——对话框
SWM32系列教程4-端口映射及串口应用
STM32H7 HAL库SPI DMA发送一直处于busy的解决办法
One brush 149 force deduction hot question-10 regular expression matching (H)
Financial management (Higher Vocational College) financial management online Assignment 1 in autumn 20
[RT thread] construction and use of --hwtimer of NXP rt10xx device driver framework
LeetCode13.罗马数字转整数(三种解法)
自动渗透测试工具核心功能简述
Electronic technology 20th autumn "Introduction to machine manufacturing" online assignment 3 [standard answer]