Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does printing of a (nil) map in golang yield a non "<nil>" result?

In golang, if you create a struct with a map in it, which is uninitialized, printing the map yields a non <nil> string.

Why does "print" of a nil map output "map[]" instead of <nil> ?

// Assume above there is a struct, a.AA, which is created but which otherwise
// has not created the map.
//output:
//map[]
//map[]
fmt.Println(a.AA)
fmt.Println(make(map[string]int64))
like image 994
jayunit100 Avatar asked Dec 11 '16 19:12

jayunit100


1 Answers

It's just for making things clear. If you run this code:

var m map[string]int64
log.Println(m == nil)
log.Printf("%T\n", m)

It will print:

$ true
$ map[string]int64

So m is actually nil at this point. A nil value (can) have a type too and the formater uses that to print out something meaningful when possible.

A map behaves like a reference type in other languages. And in Go you can call methods of a struct even if its value is nil.

So even for your own structs, you can implement fmt.Stringer interface by just defining the String() string method on your struct and whenever your struct's value is nil you can print out something more proper than <nil>. Having:

type someData struct {
    someValue string
}

func (x *someData) String() string {
    if x == nil {
        return "NO PROPER DATA HERE!"
    }

    return x.someValue
}

Then if we run:

var data *someData
log.Println(data)
data = new(someData)
data.someValue = "Aloha! :)"
log.Println(data)

The output will be:

$ NO PROPER DATA HERE!
$ Aloha! :)

See at the first line we did not get <nil> as output, despite the fact that our struct pointer is nil at that point.

like image 116
Kaveh Shahbazian Avatar answered Nov 18 '22 21:11

Kaveh Shahbazian