dongyi2993 2016-12-18 00:13
浏览 81

忽略Go中的printf值

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条回答 默认 最新

  • duanhun3273 2016-12-18 02:37
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度