printing an empty slice with fmt.Printf()

221 views
Skip to first unread message

Jochen Voss

unread,
Dec 18, 2020, 6:27:06 PM12/18/20
to golang-nuts
Hello,

I can print slices of bytes as hex strings, using code like the following:

x := []byte{0, 1, 2, 3}
fmt.Printf("%02x", x[:l])

This gives the output "00010203" as expected.  But this fails for the empty slice: running

    x := []byte{}
    fmt.Printf("%02x", x[:l])

gives "00" instead of the empty string.  See https://play.golang.org/p/rvLLqydDDE6 for a demonstration.

Is this a bug, or is this expected behaviour?

All the best,
Jochen


Marcin Romaszewicz

unread,
Dec 18, 2020, 6:40:10 PM12/18/20
to Jochen Voss, golang-nuts
It's expected behavior.

Your for loop runs once for l=0, since your condition is <=0 because len([]byte{}) is 0.

-- Marcin


--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/bb8774f3-aa17-4044-8435-ed1cd162976cn%40googlegroups.com.

Dan Kortschak

unread,
Dec 18, 2020, 7:24:07 PM12/18/20
to golan...@googlegroups.com
I think that's the question. Here's a simpler example,
https://play.golang.org/p/9Kv3PhlM-OF

That is, is 00 an expected %02x representation of a zero-length byte
slice?

The answer to that is yes; the 02 forces leading zeros. The %x verb
essentially renders bit strings as hex, so a zero-length bit string
with mandated two leading zeros is 00.

If you leave out the 02, you get the expected empty string.

https://play.golang.org/p/uVFt3lecKxf

Jochen Voss

unread,
Dec 19, 2020, 6:11:05 PM12/19/20
to golang-nuts
Dear all,

Thanks for your help.  The solution is indeed to use "%x" instead of "%02x".

My confusion was caused by the following sentence in the docs: "For compound operands such as slices and structs, the format applies to the elements of each operand".  I never spotted the relevant exception mentioned a few lines later: "However, when printing a byte slice with a string-like verb (%s %q %x %X), it is treated ... as a single item."  So the "%02" applies to the whole byte slice, and not to each byte as I had wrongly thought.

All the best,
Jochen
Reply all
Reply to author
Forward
0 new messages