当前位置:网站首页>Interviewer: why is the value nil not equal to nil?
Interviewer: why is the value nil not equal to nil?
2022-07-03 17:34:00 【Brother Xiaokun】

Xiaoming went to the interview and was asked such an interview question , Please look at the code. :
var f func()
var a *struct{}
list := []interface{}{f, a}
for _, item := range list {
if item == nil {
fmt.Println("nil")
}
}
What is the output result ?
Maybe a lot of students , You will think that the result is to output two nil.
Why? ?
because f and a Not initialized , All are nil, So it must be the same after loop traversal nil.
If your answer is the same , Then fall into the pit .
The answer is , Nothing will be output !
Let me analyze it for you :
One 、 The value and type of the variable
Let's print these two values first :
var f func()
var a *struct{}
fmt.Println(f, a)
// Output results
<nil> <nil>
We actually print like this What is printed is his value , yes nil That's right, .
But the type is not nil.
We can print his type like this :
var f func()
var a *struct{}
fmt.Printf("%T,%T \n", f, a)
// Output results
func(),*struct {}
Two 、if sentence nil Contains the judgment of type
When we are from interface Take out the object inside , Use if Judge , He doesn't just compare values , There are also types .
Take a look at this code :
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("----")
}
}
Now look at the running results :
$ go run main.go
item= <nil>
item type: func()
----
item= <nil>
item type: *struct {}
----
item= <nil>
item type: <nil>
item == nil
----
You will find that at last nil Your judgment is passed , Neither of the first two judgments passed .
3、 ... and 、 How to judge whether the value is nil
When we're writing code , It's best to try to avoid this kind of code , If you insist on writing like this , Then we can judge by the following two common ways nil.
1、 Assertion
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、 Reflection
list := []interface{}{f, a}
for _, item := range list {
if reflect.ValueOf(item).IsNil() {
fmt.Println("item is nil")
}
}
边栏推荐
- 面试官:值为 nil 为什么不等于 nil ?
- SWM32系列教程4-端口映射及串口应用
- Hongmeng fourth training
- 互联网医院HIS管理平台源码,在线问诊,预约挂号 智慧医院小程序源码
- Apache service suspended asynchronous acceptex failed
- STM32实现74HC595控制
- ArrayList analysis 3: delete elements
- Comparison of kotlin collaboration + retro build network request schemes
- VM11289 WAService. js:2 Do not have __ e handler in component:
- [combinatorics] recursive equation (general solution structure of recursive equation with multiple roots | linear independent solution | general solution with multiple roots | solution example of recu
猜你喜欢
Type conversion, variable
SQL injection database operation foundation
Baiwen.com 7 days Internet of things smart home learning experience punch in the next day
Luogu: p1155 [noip2008 improvement group] double stack sorting (bipartite graph, simulation)
vs2013已阻止安装程序,需安装IE10
How to read the source code [debug and observe the source code]
Golang unit test, mock test and benchmark test
【RT-Thread】nxp rt10xx 设备驱动框架之--hwtimer搭建和使用
[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
Embedded-c language-7
随机推荐
ArrayList分析3 : 删除元素
简单配置PostFix服务器
How SVN views modified file records
SVN完全备份svnadmin hotcopy
ES6类的继承
【RT-Thread】nxp rt10xx 设备驱动框架之--hwtimer搭建和使用
Open vsftpd port under iptables firewall
Squid service startup script
1164 Good in C
Solution to long waiting time of SSH connection to remote host
互联网医院HIS管理平台源码,在线问诊,预约挂号 智慧医院小程序源码
QT学习日记9——对话框
[combinatorics] recursive equation (special solution form | special solution solving method | special solution example)
Kubernetes resource object introduction and common commands (V) - (NFS & PV & PVC)
[combinatorics] recursive equation (example of solving recursive equation without multiple roots | complete process of solving recursive equation without multiple roots)
Enterprise custom form engine solution (XI) -- form rule engine 1
Kotlin learning quick start (7) -- wonderful use of expansion
毕业总结
Examination questions for the assignment of selected readings of British and American Literature in the course examination of Fujian Normal University in February 2022
A day's work list of an ordinary programmer