Named String Formatting

Hi Folks,

I wanted to interpolate string and get the formatted output using named place holders. The requirement is somewhat similar to Template/Text/Html package but slightly different.

Using default template packages escapes characters and gets into a route of issues than I wanted. Further, my requirement is very simple like Taking a string with named parameters & Map of interfaces should output full string as like Python format.

Tprintf(“Hello %{Name}s %{Apos}s”, map[string]interface{} {“Name” :“GoLang”, “Apos”:"!",})

ouput:
Hello GoLang !

1 Like

Just curious - what problem do named parameters solve?

You could iterate over the map and do a string replacement for each key found.

Assuming you only support %s: https://play.golang.org/p/kn24JK87VI

You could of course also parse out the format character and pass that to Sprintf.

Well, Golang is amazing by design & structure.
Since fmt.Sprintf handles both

  1. DataType based operations
    fmt.Sprintf(“String Data : %s , Int Data: %d”, “string”, 100)
  2. Indexed Data Operations.
    fmt.Sprintf(“String Data : %[1]s , Int Data: %[2]d”, map)
    would’d be nice if Golang has Named data Interpolation for a given string template.some of like this.

https://play.golang.org/p/COHKlB2RML

We have two implementations of Tprintf in this thread already, both only a handful of lines long, so it doesn’t seem to be necessary to have it in the standard library. :slight_smile:

Agreed Naming of the function could be different. but if something function solving the same purpose idea please share i can make use of it.

Nah, don’t agree. Lack of named parameters is definitely a pain. The problem it solves? Not worrying about parameter position on the right when iterating on the left. Text template is the only way to go if you have too many variables to deal with, but can be overkill.

Both implementations are not flexible enough to be really useful IMHO.

My 2 cents of course.

1 Like

Template solution is very similar:

m := map[string]interface{}{"name": "John", "age": 47}
t := template.Must(template.New("").Parse("Hi {{.name}}. Your age is {{.age}}\n"))
t.Execute(os.Stdout, m)

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.