忽略Go中的printf值

huangapple go评论74阅读模式
英文:

Ignoring printf values in Go

问题

在Printf/Sprintf/Fprintf中,有没有一种方法可以在格式化字符串中写入一个动词,即使提供了一些值,也不输出任何内容?换句话说,是否存在一个值s,使得这段代码不输出任何内容?

在C语言中,答案很简单:空字符串,因为多余的值会被忽略。在Go语言中,空的格式化字符串会输出%!(EXTRA int=42),我认为这是一件好事,因为格式化字符串很可能是错误的。在Python中,甚至会抛出"TypeError: not all arguments converted during string formatting"的错误。但是,如果我们真的想要忽略、跳过、取消这些值,我们该如何说服Printf我们的良好意图呢?

如果值是一个字符串,很容易:将其截断为零:

fmt.Printf("nothing%.0s here", "foul")

甚至可以省略该动词中的0,我在挖掘我问题的一个bash版本后意识到这一点。但是如果值是一个数字呢?

如果你想知道为什么不简单地省略多余的值:上下文是只能修改格式化字符串,作为函数的参数。函数体将一些预定类型的值传递给格式化字符串,如这个简化的playground示例中所示。通常,传入的格式化字符串希望表示该值,但有时您可能希望忽略它。当然,函数可以发展起来,接受一个接口而不是格式化字符串,但我只是想知道Printf是否能像在C语言中那样独立完成这个任务。

英文:

Is there a way to write a verb in a format string that outputs nothing, even though some values are supplied to Printf/Sprintf/Fprintf? In other words, is there a value of s for which this code outputs nothing?

fmt.Printf(s, 42)

In C, the answer is easy: the empty string, because the superfluous value is ignored. In Go, an empty format string leads to the output %!(EXTRA int=42). Which I consider a good thing, because the format string is most likely wrong. Python even throws "TypeError: not all arguments converted during string formatting" in that situation. But if we truly want to gobble up, ignore, skip, cancel the values, how could we convince Printf of our good intentions?

If the value is a string, it's easy: truncate to zero:

    fmt.Printf("nothing%.0s here", "foul")

You could even omit the 0 in that verb, I realised after digging up a bash version of my question. But what if the value is a number?

If you wonder, why not simply omit superfluous values: the context is that only the format string can be touched, being the parameter of a function. The function body feeds the format some value(s) of predetermined types, such as in this simplified playground example. Usually, the format passed in wants to represent the value, but sometimes you may want to ignore it. Of course the function could grow up and accept an interface instead of a format string, but I'm just wondering if Printf could pull it off on its own like it can in C.

答案1

得分: 2

这可能不完全符合你的要求,但值得看一下text/template包。然后你可以使用Parse("{{.Name}}的物品由{{.Material}}制成")定义一个模板,并将一个包含键为"Name""Material"map[string]string传递给Execute方法。这样做的额外好处是格式字符串还可以安排值的输出顺序。

英文:

This may not be exactly what you're looking for but it's worth looking at the text/template package. Then you could define a template with Parse("{{.Name}} items are made of {{.Material}}") and pass in to Execute a map[string]string containing keys "Name" and "Material". This has the added advantage that the format string can also arrange the output order of values.

huangapple
  • 本文由 发表于 2016年12月18日 08:13:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/41204322.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定