[英]Interpreted string literals in Go
为日志消息或stderr消息编写长而翔实的字符串通常很不错。 Python使用逗号分隔的字符串文字来处理此问题,例如:
log.warn("The operation failed on the %d iteration. "
"Resumed on the %d iteration.",
failed, resumed)
通过使用反引号,Go似乎对原始字符串文字有解决方案,但是我找不到解释字符串文字的任何样式指南。 我是否缺少某些内容,或者除了使用变量之外别无选择? 例如
msg := fmt.Sprintf("The operation failed on the %d iteration. ", failed)
msg += fmt.Sprintf("Resumed on the %d iteration.", resumed)
log.println(msg)
您可以使用+
:
fmt.Printf("The operation failed on the %d iteration. "+
"Resumed on the %d iteration.",
failed, resumed,
)
操场 。
标准库中有一些使用+
示例,其中大多数在测试中。 例子 有关更多示例,请参见以下搜索请求: http : //golang.org/search?q=%22\\%2B\\n 。
首先,我什至看不到您的python示例如何工作。 这是类似的东西:
>>> import logging
>>> logging.warn("foo %d", "bar %d", 1,2)
原因:
TypeError: %d format: a number is required, not str
其次,在Go中,您有几种选择:
多行字符串:
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))
两者看起来都更好,并且可能比字符串连接要快。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.