Go中解释的字符串文字

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)

为日志消息或stderr消息编写长而翔实的字符串通常很不错。 Python使用逗号分隔的字符串文字来处理此问题,例如: p>

  log.warn(“%d迭代操作失败。” 
“%d迭代恢复。  “,
失败,恢复)
  code>  pre> 
 
 

Go似乎使用反引号解决了原始字符串文字的问题,但我找不到任何样式指南 解释的字符串文字。 我是否缺少某些内容,或者除了使用变量之外别无选择? 例如, p>

  msg:= fmt.Sprintf(“该操作在%d迭代上失败。”,失败)
msg + = fmt.Sprintf(“在%d上恢复 迭代。”,恢复)
log.println(msg)
  code>  pre> 
  div>

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.

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 .