当前位置:网站首页>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")
}
}
边栏推荐
- Svn full backup svnadmin hotcopy
- Internet hospital his management platform source code, online consultation, appointment registration smart hospital applet source code
- vs code 插件 koroFileHeader
- Golang unit test, mock test and benchmark test
- Graduation summary
- Baiwen.com 7 days Internet of things smart home learning experience punch in the next day
- Qt调节Win屏幕亮度和声音大小
- 【RT-Thread】nxp rt10xx 设备驱动框架之--Audio搭建和使用
- [combinatorics] recursive equation (general solution structure of recursive equation with multiple roots | linear independent solution | general solution with multiple roots | solution example of recu
- [RT thread] NXP rt10xx device driver framework -- pin construction and use
猜你喜欢

Kubernetes resource object introduction and common commands (V) - (NFS & PV & PVC)

Design e-commerce spike
![[error reporting] omp: error 15: initializing libiomp5md dll, but found libiomp5md. dll already initialized.](/img/a0/4fc0e0741aad2885873e60f2af3387.jpg)
[error reporting] omp: error 15: initializing libiomp5md dll, but found libiomp5md. dll already initialized.

互联网医院HIS管理平台源码,在线问诊,预约挂号 智慧医院小程序源码

Embedded-c language-7

TensorBoard快速入门(Pytorch使用TensorBoard)
![[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 quick start (pytoch uses tensorboard)

Unity notes unityxr simple to use

POM in idea XML graying solution
随机推荐
[error reporting] omp: error 15: initializing libiomp5md dll, but found libiomp5md. dll already initialized.
Dagong 21 autumn "power plant electrical part" online operation 1 [standard answer] power plant electrical part
Host based intrusion system IDS
Embedded-c language-7
Squid service startup script
PHP processing - watermark images (text, etc.)
Luogu: p2685 [tjoi2012] Bridge
[combinatorics] recursive equation (solution of linear non-homogeneous recursive equation with constant coefficients | standard form and general solution of recursive equation | proof of general solut
UE4 official charging resources, with a total price of several thousand
Collection of the most beautiful graduation photos in the graduation season, collection of excellent graduation photos
基于主机的入侵系统IDS
毕业总结
ArrayList分析3 : 删除元素
How to enforce parameters in PowerShell- How do I make parameters mandatory in PowerShell?
网络硬盘NFS的安装与配置
面试官:值为 nil 为什么不等于 nil ?
How to read the source code [debug and observe the source code]
[RT thread] construction and use of --hwtimer of NXP rt10xx device driver framework
List of financial products in 2022
Swm32 series Tutorial 4 port mapping and serial port application