英文:
Null vs nil in golang?
问题
我今天遇到了一个奇怪的错误。我有一个函数:
func Foo(s *someStruct) {
fmt.Printf("s is %v\n", s)
if s != nil {
fmt.Printf("s is not nil")
...
}
}
我会这样调用这个函数:
var s *someStruct
Foo(s)
然后我决定将结构体转换为接口:
func Foo(s someStructInterface) {
fmt.Printf("s is %v\n", s)
if s != nil {
fmt.Printf("s is not nil")
...
}
}
这给了我一个奇怪的输出:
s is null
s is not nil
而我期望得到的是s is nil,这通常是我得到的结果。在这种情况下,Go语言中的null和nil有什么区别,我如何检查某个值是否为null或nil以正确执行代码?
英文:
I ran into a strange bug today. I had a function:
func Foo(s *someStruct) {
fmt.Printf("s is %v\n", s)
if s!=nil {
fmt.Printf("s is not nil")
...
}
}
I would call the function like:
var s *someStruct
Foo(s)
And then I decided to convert the structure into interface:
func Foo(s someStructInterface) {
fmt.Printf("s is %v\n", s)
if s!=nil {
fmt.Printf("s is not nil")
...
}
}
Which gave me a strange output:
s is null
s is not nil
While I expected to get s is nil, which is what I was getting usually. What is the difference between null and nil in this scenario in Go and how can I check if something is null or nil to execute the code properly?
答案1
得分: 4
一个接口值包含对类型和值的引用。在下面的代码中:
var s *someStruct
Foo(s)
传递给Foo的接口值包含对类型*someStruct的引用和一个nil。
语句fmt.Printf("s is %v\n", s)输出s is <nil>,原因如下:
%v格式使用类型的默认格式打印值。值s包含一个指针类型。指针类型的默认格式是%p。%p格式将nil指针打印为<nil>。
表达式s != nil的结果为true,因为只有当类型引用为nil时,接口值才等于nil。在这种情况下,接口值引用了类型*someStruct。
英文:
An interface value contains a reference to a type and a value. In the following code:
var s *someStruct
Foo(s)
the interface value passed to Foo contains a reference to the type *someStruct and a nil.
The statement fmt.Printf("s is %v\n", s) outputs s is <nil> because of the following:
The %v format prints a value using the default format for the type. The value s contains a pointer type. The default format for a pointer type is %p. The %p format prints nil pointers as <nil>.
The expression s != nil evaluates to true because an interface value is equal to nil if and only if the type reference is nil. In this case, the interface value references the type *someStruct.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论