Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

printf

go

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) 
like image 403
425nesp Avatar asked Oct 29 '14 07:10

425nesp


People also ask

What is %V in printf?

The verbs behave analogously to those of Printf. For example, %x will scan an integer as a hexadecimal number, and %v will scan the default representation format for the value. The Printf verbs %p and %T and the flags # and + are not implemented.

What is FMT printf?

Faraz Karim. The fmt. Printf function in the GO programming language is a function used to print out a formatted string to the console. fmt. Printf supports custom format specifiers and uses a format string to generate the final output string .


Video Answer


2 Answers

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

like image 166
James Henstridge Avatar answered Oct 09 '22 14:10

James Henstridge


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)) } 
like image 28
Zombo Avatar answered Oct 09 '22 16:10

Zombo