Steve Crook
Steve Crook

Reputation: 1055

Interpreted string literals in Go

It's frequently nice to write long, informative strings for log messages or stderr messages. Python handles this with comma separated string literals, like:

log.warn("The operation failed on the %d iteration. "
         "Resumed on the %d iteration.",
         failed, resumed)

Go appears to have a solution for raw string literals, by using back quotes but I can't find any style guide for interpreted string literals. Am I missing something or is there no option but to use a variable? E.g.

msg := fmt.Sprintf("The operation failed on the %d iteration. ", failed)
msg += fmt.Sprintf("Resumed on the %d iteration.", resumed)
log.println(msg)

Upvotes: 3

Views: 4131

Answers (2)

Ainar-G
Ainar-G

Reputation: 36249

You could just use +:

fmt.Printf("The operation failed on the %d iteration. "+
    "Resumed on the %d iteration.",
    failed, resumed,
)

Playground.

There are examples in the standard library of using + for that, most of them in tests. Example. For more examples see this search request: http://golang.org/search?q=%22\%2B\n.

Upvotes: 2

Not_a_Golfer
Not_a_Golfer

Reputation: 49255

First of all, I don't see how your python example would even work. Here's something similar:

>>> import logging
>>> logging.warn("foo %d", "bar %d", 1,2)

causes:

 TypeError: %d format: a number is required, not str

Second, in Go, you have a few options:

Multi-line strings:

msg := fmt.Sprintf(`The operation failed on the %d iteration. 
            Resumed on the %d iteration.`, 2, 3)
log.Println(msg)

But this will result in a multiline message.

Another option:

  log.Println(fmt.Sprintf("The operation failed on the %d iteration. ", failed), 
              fmt.Sprintf("Resumed on the %d iteration.", resumed))

which both looks better and will probably be faster than string concatenation.

Upvotes: 0

Related Questions