425nesp
425nesp

Reputation: 7583

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)

Upvotes: 68

Views: 14051

Answers (3)

shashank kesharwani
shashank kesharwani

Reputation: 1

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
}

Upvotes: 0

Zombo
Zombo

Reputation: 1

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))
}

Upvotes: 2

James Henstridge
James Henstridge

Reputation: 43909

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

Upvotes: 110

Related Questions