Reputation: 1639
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.
Upvotes: 2
Views: 2171
Reputation: 36134
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.
Upvotes: 2