Null vs nil in golang?

huangapple go评论70阅读模式
英文:

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(&quot;s is %v\n&quot;, s) outputs s is &lt;nil&gt; 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 &lt;nil&gt;.

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.

huangapple
  • 本文由 发表于 2016年2月17日 05:56:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/35443787.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定