Enrique Alcazar
Enrique Alcazar

Reputation: 381

No placeholders in format string

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?

Upvotes: 0

Views: 3518

Answers (1)

icza
icza

Reputation: 418435

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.

Upvotes: 8

Related Questions