Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Positional arguments in Go Printf?

In many other modern languages, "printf" type facilities allow the selection of arguments for substitution into the format string by their numerical position, rather than only in the order they appear. E.g. in Java:

System.out.printf("This is arg 2 %2$s and this is arg 1 %1$s\n", "first", "second")

produces the output:

This is arg 2 second and this is arg 1 first

I believe this is even specified by Posix in some context, since localization often requires language-specific word order.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Does Go support this capability? I’ve tried the obvious format string, but that didn’t work.

>Solution :

Yes, that is possible; from the docs:

In Printf, Sprintf, and Fprintf, the default behavior is for each formatting verb to format successive arguments passed in the call. However, the notation [n] immediately before the verb indicates that the nth one-indexed argument is to be formatted instead.

Applying this to your example, you would have

fmt.Printf("This is arg 2 %[2]s and this is arg 1 %[1]s\n", "first", "second")
// prints 'This is arg 2 second and this is arg 1 first'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading