Is there a way to reuse an argument in fmt.Printf?
I have a situation where I want to use my printf
argument twice.
fmt.Printf("%d %d", i, i)
Is there a way to tell fmt.Printf
to just reuse the same i
?
fmt.Printf("%d %d", i)
You can use the [n]
notation to specify explicit argument indexes like so:
fmt.Printf("%[1]d %[1]d\n", i)
Here is a full example you can experiment with: http://play.golang.org/p/Sfaai-XgzN
Another option is text/template:
package main
import (
"strings"
"text/template"
)
func format(s string, v interface{}) string {
t, b := new(template.Template), new(strings.Builder)
template.Must(t.Parse(s)).Execute(b, v)
return b.String()
}
func main() {
i := 999
println(format("{{.}} {{.}}", i))
}