FAQ
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?

--

Search Discussions

  • Minux at Nov 1, 2012 at 12:06 pm

    On Thu, Nov 1, 2012 at 7:51 PM, Nate Finch wrote:

    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?
    I'd recommend text/template <http://golang.org/pkg/text/template> for this,
    just pass a map[string]string to tmpl.Execute.

    --
  • Nate Finch at Nov 1, 2012 at 12:24 pm
    Yes! Brilliant, thank you. I hadn't thought about templates as more
    complex string formatting, but that's perfect.
    On Thursday, November 1, 2012 8:06:18 AM UTC-4, minux wrote:


    On Thu, Nov 1, 2012 at 7:51 PM, Nate Finch <nate....@gmail.com<javascript:>
    wrote:
    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?
    I'd recommend text/template <http://golang.org/pkg/text/template> for
    this, just pass a map[string]string to tmpl.Execute.
    --

Related Discussions

Discussion Navigation
viewthread | post
Discussion Overview
groupgolang-nuts @
categoriesgo
postedNov 1, '12 at 11:51a
activeNov 1, '12 at 12:24p
posts3
users2
websitegolang.org

2 users in discussion

Nate Finch: 2 posts Minux: 1 post

People

Translate

site design / logo © 2021 Grokbase