otm
otm

Reputation: 745

Golang print "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!

Upvotes: 9

Views: 14865

Answers (2)

harold ramos
harold ramos

Reputation: 651

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.

Upvotes: -3

JimB
JimB

Reputation: 109318

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>

Upvotes: 15

Related Questions