当前位置:网站首页>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")
}
}
边栏推荐
- [UE4] brush Arctic pack high quality Arctic terrain pack
- 简单配置PostFix服务器
- 【RT-Thread】nxp rt10xx 设备驱动框架之--Pin搭建和使用
- Electronic Science and technology 20th autumn "Microcomputer Principle and application" online assignment 2 [standard answer]
- Golang unit test, mock test and benchmark test
- 鸿蒙第四次培训
- Detailed explanation of common network attacks
- Comparison of kotlin collaboration + retro build network request schemes
- QT adjust win screen brightness and sound size
- Luogu: p2685 [tjoi2012] Bridge
猜你喜欢
Hongmeng third training
Embedded-c language-7
How to purchase Google colab members in China
2021 ICPC regional competition (Shanghai) g.edge groups (tree DP)
Notes on problems -- watching videos on edge will make the screen green
Life is still confused? Maybe these subscription numbers have the answers you need!
Qt调节Win屏幕亮度和声音大小
【RT-Thread】nxp rt10xx 设备驱动框架之--Pin搭建和使用
面试官:值为 nil 为什么不等于 nil ?
PS screen printing brush 131, many illustrators have followed suit
随机推荐
Financial management (Higher Vocational College) financial management online Assignment 1 in autumn 20
Applet setting multi account debugging
[combinatorics] recursive equation (special solution example 1 Hannover tower complete solution process | special solution example 2 special solution processing when the characteristic root is 1)
Swm32 series Tutorial 4 port mapping and serial port application
Baiwen.com 7 days Internet of things smart home learning experience punch in the next day
Simple use of unity pen XR grab
Cloud primordial weekly | CNCF released the 2021 cloud primordial development status report, which was released on istio 1.13
SQL injection database operation foundation
[combinatorics] recursive equation (summary of the solution process of recursive equation | homogeneous | double root | non-homogeneous | characteristic root is 1 | exponential form | the bottom is th
Brief introduction to the core functions of automatic penetration testing tool
[combinatorics] recursive equation (the non-homogeneous part is an exponential function and the bottom is the characteristic root | example of finding a special solution)
Test your trained model
[combinatorics] recursive equation (general solution structure of recursive equation with multiple roots | linear independent solution | general solution with multiple roots | solution example of recu
Cross border e-commerce: advantages of foreign trade enterprises in overseas social media marketing
Electronic Science and technology 20th autumn "Microcomputer Principle and application" online assignment 2 [standard answer]
Notes on problems -- watching videos on edge will make the screen green
Leetcode13. Roman numeral to integer (three solutions)
[combinatorics] recursive equation (special solution form | special solution solving method | special solution example)
[combinatorics] recursive equation (example of solving recursive equation without multiple roots | complete process of solving recursive equation without multiple roots)
STM32实现74HC595控制