goprintfbackslashgofmt

How to print backslash in go?


I have the following code snippet:

const byte1 = 0x19;
const byte2 = 0x45;
msg := fmt.Sprintf("\\x%x\\x%x message", byte1, byte2)
log.Info("Learning go fmt", "msg", msg)

I get this:

msg="\\x19\\x45 message"

Why is the backslash duplicated? According to this website, \\ within a format should yield \.


Solution

  • @nilsocket's comment is correct. The problem is that I'm using the Ethereum log package. It unescapes the string. If I do:

    fmt.Println("\\x%x\\x%x message", byte1, byte2)
    

    It works perfectly fine.