%v for []string{} and []string{""}

136 views
Skip to first unread message

Brian Candler

unread,
Mar 15, 2021, 8:18:46 AM3/15/21
to golang-nuts
I was slightly surprised to discover that the Print() output for an empty slice, and a 1-element slice containing the empty string, are the same:


It does follow logically from the rules.  I guess I need to train myself to use %q or %#v.

tapi...@gmail.com

unread,
Mar 17, 2021, 5:24:46 PM3/17/21
to golang-nuts
Printing a nil slice also get the same output [].

I remembered Rob Pike ever said in an issue thread that this can't be changed now for compatibility reason.

Brian Candler

unread,
Mar 18, 2021, 6:31:32 AM3/18/21
to golang-nuts
Sure.  I don't have a problem with nil slice and empty slice showing the same, because in all important ways they behave the same - i.e. they have len() of 0, you can append() to them, etc.  The only behavioural difference I can think of is if you explicitly test "foo == nil".

However, a slice with len=1 that showed the same as one with len=0, was what confused me :-)

On reflection, %v is intentionally ambiguous.  There are other examples, e.g.
- []string{"a","b"} and []string{"a b"}
- []string{"", ""} and []string{" "}

Kevin Chowski

unread,
Mar 18, 2021, 4:47:15 PM3/18/21
to golang-nuts
The "%#v" print verb is intended to be used for unambiguous printing of a type, but that means it will have a prefix of `[]string` in order to ensure the type is unambiguous. I personally use %q a lot any time I know I have a string (or set of strings) which might be ambiguous in some way, but I don't want the `[]string` prefix in there. See: https://play.golang.org/p/70Ryd50IGt6
Reply all
Reply to author
Forward
0 new messages