Golang打印”nil”

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

Golang print "nil"

问题

我正在阅读Golang教程:https://tour.golang.org/moretypes/10
我对fmt.Println如何打印nil值感到困惑,希望你能帮助我。

package main

import "fmt"

func main() {
    var z []int
    fmt.Println("z: ", z)
    if z == nil {
        fmt.Println("z is nil!")
    } 
    fmt.Println("nil:", nil)
}

结果是:

z:  []
z is nil!
nil: <nil>

既然z是nil,为什么z被打印为[]而不是<nil>

谢谢!

英文:

i am reading the golang tutorial: https://tour.golang.org/moretypes/10
And i am confused about how fmt.Println prints the nil value, hope you could help me out.

package main

import &quot;fmt&quot;

func main() {

    var z []int
    fmt.Println(&quot;z: &quot;, z)
    if z == nil {
	    fmt.Println(&quot;z is nil!&quot;)
    } 
    fmt.Println(&quot;nil:&quot;, nil)
}

the result is:

z:  []
z is nil!
nil: &lt;nil&gt;

Since z is a nil, why is z printed as [] but not &lt;nil&gt;?

thanks!

答案1

得分: 13

fmt包使用反射来确定要打印的内容。由于z的类型是切片,fmt使用[]表示法。

由于切片、通道、接口和指针都可以是nil,当可以时,fmt打印出不同的内容是很有帮助的。如果你想要更多的上下文,请使用%v格式:http://play.golang.org/p/I1SAVzlv9f

var a []int
var b chan int
var c *int
var e error
fmt.Printf("a:%#v\n", a)
fmt.Printf("b:%#v\n", b)
fmt.Printf("c:%#v\n", c)
fmt.Printf("e:%#v\n", e)

打印结果:

a:[]int(nil)
b:(chan int)(nil)
c:(*int)(nil)
e:<nil>
英文:

The fmt package uses reflection to determine what to print. Since the type of z is a slice, fmt uses the [] notation.

Since slices, channels, interfaces and pointers can all be nil, it helpful if fmt prints something different when it can. If you want more context, use the %v format: http://play.golang.org/p/I1SAVzlv9f

var a []int
var b chan int
var c *int
var e error
fmt.Printf(&quot;a:%#v\n&quot;, a)
fmt.Printf(&quot;b:%#v\n&quot;, b)
fmt.Printf(&quot;c:%#v\n&quot;, c)
fmt.Printf(&quot;e:%#v\n&quot;, e)

Prints:

a:[]int(nil)
b:(chan int)(nil)
c:(*int)(nil)
e:&lt;nil&gt;

答案2

得分: -1

单词"nil"的意思是:未初始化。
在这种情况下,你正在初始化幻灯片,但尚未分配任何值。
请记住,指针、接口、通道和幻灯片(PICS)都已经初始化。

英文:

The word nil means : not initialized.
In this case you are initializing the slide but no values have bean assigned yet.
Remember PICS (Pointers, Interfaces, CHANNELS , and SLIDES )are all already
initialized.

huangapple
  • 本文由 发表于 2015年9月1日 03:30:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/32318583.html
匿名

发表评论

匿名网友

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

确定