2014-10-06 63 views
2

爲日誌消息或stderr消息編寫長的信息字符串通常很不錯。 Python的處理這與逗號分隔字符串文字,如:Go中的解釋字符串文字

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

圍棋似乎對原始字符串字面量的解決方案,通過使用反引號,但我找不到解釋字符串字面任何風格指南。我是否錯過了一些東西,或者有沒有選擇,只能使用一個變量?例如。

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

你真正要問的是如何在源文件的下一行繼續聲明。正確? – RickyA 2014-10-06 13:08:16

回答

1

首先,我沒有看到你的Python例子甚至可以工作。下面是類似的東西:

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

原因:

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

其次,在走了,你有幾種選擇:

多行字符串:

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

但這決導致多行消息。

另一種選擇:

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

這兩者看起來更好,可能比字符串連接快。

+1

我將一個不需要的逗號插入我的Python示例中。放下兩個琴絃之間的那個,它就會起作用。你的Sprintf例子很好,謝謝。 – 2014-10-06 13:06:13

2

你可以只使用+

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

Playground

在標準庫中有一些使用+的例子,其中大多數在測試中。 Example。有關更多示例,請參閱此搜索請求:http://golang.org/search?q=%22\%2B\n