Named string format variables?

3,008 views
Skip to first unread message

Nate Finch

unread,
Nov 1, 2012, 7:51:11 AM11/1/12
to golan...@googlegroups.com
Is there a way to name string format variables, or otherwise correlate the format with the parameters by something other than their order in the source code?

For example:

bill := "Bill"
max := "Max"
s := "%person walks his dog %dog down the street."

fmt.Sprintf(s, person: bill, dog: max)

Result: 
"Bill walks his dog Max down the street."

The reason for this is that I want to be able to arbitrarily change the format string based on a configuration file, without having to worry about the order of the format parameters.

Is there a built-in way to do this, or am I stuck implementing something myself?

minux

unread,
Nov 1, 2012, 8:05:48 AM11/1/12
to Nate Finch, golan...@googlegroups.com
I'd recommend text/template for this, just pass a map[string]string to tmpl.Execute.

Nate Finch

unread,
Nov 1, 2012, 8:24:44 AM11/1/12
to golan...@googlegroups.com, Nate Finch
Yes!   Brilliant, thank you.  I hadn't thought about templates as more complex string formatting, but that's perfect.
Reply all
Reply to author
Forward
0 new messages