英文:
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 "fmt"
func main() {
var z []int
fmt.Println("z: ", z)
if z == nil {
fmt.Println("z is nil!")
}
fmt.Println("nil:", nil)
}
the result is:
z: []
z is nil!
nil: <nil>
Since z is a nil, why is z printed as []
but not <nil>
?
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("a:%#v\n", a)
fmt.Printf("b:%#v\n", b)
fmt.Printf("c:%#v\n", c)
fmt.Printf("e:%#v\n", e)
Prints:
a:[]int(nil)
b:(chan int)(nil)
c:(*int)(nil)
e:<nil>
答案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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论