Is there a way to reuse an argument in fmt.Printf?
Asked Answered
D

3

63

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)
Dispensary answered 29/10, 2014 at 7:20 Comment(0)
G
103

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

Griffin answered 29/10, 2014 at 7:24 Comment(2)
If you are using this to replace a different format like %s, remember to swap out the d in this answer for s. I.e. fmt.Printf("%[1]s %[1]s\n", i)Nijinsky
this is also available for all formated prints, like Sprintf and FprintfRemscheid
F
2

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))
}
Fenian answered 14/7, 2021 at 23:14 Comment(0)
D
0

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
}
Daybreak answered 21/1, 2024 at 14:33 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.