当前位置:网站首页>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")
}
}
边栏推荐
- Examination questions for the assignment of selected readings of British and American Literature in the course examination of Fujian Normal University in February 2022
- [UE4] brush Arctic pack high quality Arctic terrain pack
- Select 3 fcpx plug-ins. Come and see if you like them
- An example of HP array card troubleshooting
- [combinatorics] recursive equation (general solution structure of recursive equation with multiple roots | linear independent solution | general solution with multiple roots | solution example of recu
- [combinatorics] recursive equation (the problem of solving recursive equation with multiple roots | the problem is raised)
- Golang单元测试、Mock测试以及基准测试
- 设计电商秒杀
- Notes on problems -- watching videos on edge will make the screen green
- Electronic technology 20th autumn "Introduction to machine manufacturing" online assignment 3 [standard answer]
猜你喜欢
[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
Qt调节Win屏幕亮度和声音大小
New library online | cnopendata complete data of Chinese insurance institution outlets
1146_ SiCp learning notes_ exponentiation
问题随记 —— 在 edge 上看视频会绿屏
Collection of the most beautiful graduation photos in the graduation season, collection of excellent graduation photos
鸿蒙第四次培训
【RT-Thread】nxp rt10xx 设备驱动框架之--rtc搭建和使用
How to read the source code [debug and observe the source code]
1164 Good in C
随机推荐
An example of HP array card troubleshooting
ArrayList分析3 : 删除元素
How to train mask r-cnn model with your own data
QT adjust win screen brightness and sound size
Simple use of unity pen XR grab
Qt调节Win屏幕亮度和声音大小
问题随记 —— 在 edge 上看视频会绿屏
1147_ Makefile learning_ Target files and dependent files in makefile
SWM32系列教程4-端口映射及串口应用
绝对定位时元素水平垂直居中
RDS数据库的监测页面在哪看?
Unity notes unityxr simple to use
Examination questions for the assignment of selected readings of British and American Literature in the course examination of Fujian Normal University in February 2022
First day of rhcsa study
Wechat applet for the first time
1164 Good in C
How SVN views modified file records
[combinatorics] recursive equation (four cases where the non-homogeneous part of a linear non-homogeneous recursive equation with constant coefficients is the general solution of the combination of po
[combinatorics] recursive equation (the non-homogeneous part is an exponential function and the bottom is the characteristic root | example of finding a special solution)
New library online | cnopendata complete data of Chinese insurance institution outlets