0

This question is about best practices when formatting strings in Go.

Whenever I'm using the print library like so:

log.Printf("Greeting:",resp.GetMessage())

I get a warning from my IDE (Goland) saying:

No placeholders in format string

What does that mean? What would a proper print look like?

Enrique Alcazar
  • 381
  • 7
  • 21
  • 3
    It means you forgot the `%s`. – tkausl Sep 24 '19 at 09:04
  • 1
    It is not specifically about log structure, but string formatting as you use `Print**f**`. So, did you try `log.Printf("Greeting:%s\n",resp.GetMessage())`? – vahdet Sep 24 '19 at 09:07
  • 1
    @vahdet you never need a trailing `\n` in `log` calls, just so you know. – Adrian Sep 24 '19 at 13:38
  • It was a fair question, I tried to specify it as much as possible and followed all of the patterns, and yet you guys downvoted and got me banned, thanks for that... – Enrique Alcazar Sep 25 '19 at 15:55

1 Answers1

8

log.Printf() expects a format string as its first argument:

func Printf(format string, v ...interface{})

A format string is a string where you may use verbs with modifiers to lay out how you want the result string to look like. A format string without any verbs is likely an error (indicating you probably forgot something from it, or if it truly does not need verbs, you shouldn't use Pritnf() which expects a format string). You can read more about format strings and their Go syntax at the doc of the fmt package.

For example, this is a format string:

"Greeting: %s"

This is how it would be used:

log.Printf("Greeting: %s", resp.GetMessage())

This is a very simple example and does not warrant formatted output. If you don't have a format string, use log.Print() or log.Println() instead (they don't require a format string):

log.Println("Greeting:", resp.GetMessage())

The Printf() variant comes handy when you need more complex formatting, not just log 2 strings (concatenated).

For example:

log.Printf("Hi, my name is %s, and I'm %d years old.", "Bob", 22)

Output will be (try it on the Go Playground):

2009/11/10 23:00:00 Hi, my name is Bob, and I'm 22 years old.
icza
  • 389,944
  • 63
  • 907
  • 827