%v display of nil map

134 views
Skip to first unread message

Andrew Athan

unread,
Jan 25, 2023, 10:21:09 AM1/25/23
to golang-nuts
I'm sure I'm not the first to say this, but here's my +1:

It seems wrong to me that golang displays nil-valued reference types as an empty instance of the type with no indication that the reference is nil.

E.g.
```
var m map[string]string
fmt.Printf("%+v",m)
```

displays as "map[]"

I think it would be better to display something like "<nil>map[]", don't you?

Motivation: While the nil map does act like a map[] for reads, it does not act like one for writes, and debugging via prints can therefore be confusing for new users.

A.

Dan Kortschak

unread,
Jan 25, 2023, 3:05:16 PM1/25/23
to golan...@googlegroups.com
For debugging, use %#v. https://go.dev/play/p/UlvaFg5Z_lB

Andrew Athan

unread,
Jan 26, 2023, 11:24:13 AM1/26/23
to golan...@googlegroups.com
I should have RTFMed, but even there, the nil display issue is not highlighted :)  Thanks. It seemed odd that there wasn't already a way. It might be good to highlight this feature in the right places. I'm not sure if golangdocs.com is the official easy on-ramp for golang but if so, at https://golangdocs.com/string-formatting-in-golang 's section 1.5 the wording "print the Go-representation of the struct." could read "... the struct, and explicitly show <nil> valued slices and maps."; and the example could show this case.

The same applies to the official documentation for the fmt package, which states (in the comments of one example): " // The %#v form (the # is called a "flag" in this context) shows the map in
// the Go source format. Maps are printed in a consistent order, sorted" without reference to how nils are treated.

In addition, I would argue that the unadorned %v documentation should mention that nil values are folded into the "empty" representation.

Anyway, as time allows I'll find the doc source and submit PRs implementing the above suggestions.

Thank you for pointing this solution out.
Andrew

--
You received this message because you are subscribed to a topic in the Google Groups "golang-nuts" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/golang-nuts/6qKpr5_SXYA/unsubscribe.
To unsubscribe from this group and all its topics, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/6e278c5a183432315bb86e19b4c4f7794c9b56ab.camel%40kortschak.io.
Reply all
Reply to author
Forward
0 new messages