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)
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
Sprintf
and Fprintf
–
Remscheid 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))
}
Usually a Printf format string containing multiple % verbs would require the same number of extra operands, but the [n] “adverbs” after % tell Printf to use the nth operand over and over again.
package main
import "fmt"
func main() {
a := 1
fmt.Printf("%d %[1]T\n", a) //1 int
b, c := "apple", 3.14
fmt.Printf("%s %[1]T %g %[2]T", b, c) //apple string 3.14 float64
}
© 2022 - 2025 — McMap. All rights reserved.
%s
, remember to swap out thed
in this answer fors
. I.e.fmt.Printf("%[1]s %[1]s\n", i)
– Nijinsky