Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of Python string.format in Go?

Tags:

python

string

go

In Python, you can do this:

"File {file} had error {error}".format(file=myfile, error=err)

or this:

"File %(file)s had error %(error)s" % {"file": myfile, "error": err}

In Go, the simplest option is:

fmt.Sprintf("File %s had error %s", myfile, err)

which doesn't let you swap the order of the parameters in the format string, which you need to do for I18N. Go does have the template package, which would require something like:

package main

import (
    "bytes"
    "text/template"
    "os"
)

func main() {
    type Params struct {
        File string
        Error string
    }

    var msg bytes.Buffer

    params := &Params{
        File: "abc",
        Error: "def",
    }

    tmpl, _ := template.New("errmsg").Parse("File {{.File}} has error {{.Error}}")
    tmpl.Execute(&msg, params)
    msg.WriteTo(os.Stdout)
}

which seems like a long way to go for an error message. Is there a more reasonable option that allows me to give string parameters independent of order?

like image 826
Scott Deerwester Avatar asked Nov 25 '16 19:11

Scott Deerwester


People also ask

How do I format a string in go?

To format strings in Go, we use functions including fmt. Printf , fmt. Sprintf , or fmt. Fscanf .

Does Go have string interpolation?

The Go Sprintf method from fmt package serves just this: String Interpolation.

What is format string in Python?

Formatted string literals are a Python parser feature that converts f-strings into a series of string constants and expressions. They then get joined up to build the final string.


4 Answers

With strings.Replacer

Using strings.Replacer, implementing a formatter of your desire is very easy and compact.

func main() {
    file, err := "/data/test.txt", "file not found"

    log("File {file} had error {error}", "{file}", file, "{error}", err)
}

func log(format string, args ...string) {
    r := strings.NewReplacer(args...)
    fmt.Println(r.Replace(format))
}

Output (try it on the Go Playground):

File /data/test.txt had error file not found

We can make it more pleasant to use by adding the brackets to the parameter names automatically in the log() function:

func main() {
    file, err := "/data/test.txt", "file not found"

    log2("File {file} had error {error}", "file", file, "error", err)
}

func log2(format string, args ...string) {
    for i, v := range args {
        if i%2 == 0 {
            args[i] = "{" + v + "}"
        }
    }
    r := strings.NewReplacer(args...)
    fmt.Println(r.Replace(format))
}

Output (try it on the Go Playground):

File /data/test.txt had error file not found

Yes, you could say that this only accepts string parameter values. This is true. With a little more improvement, this won't be true:

func main() {
    file, err := "/data/test.txt", 666

    log3("File {file} had error {error}", "file", file, "error", err)
}

func log3(format string, args ...interface{}) {
    args2 := make([]string, len(args))
    for i, v := range args {
        if i%2 == 0 {
            args2[i] = fmt.Sprintf("{%v}", v)
        } else {
            args2[i] = fmt.Sprint(v)
        }
    }
    r := strings.NewReplacer(args2...)
    fmt.Println(r.Replace(format))
}

Output (try it on the Go Playground):

File /data/test.txt had error 666

A variant of this to accept params as a map[string]interface{} and return the result as a string:

type P map[string]interface{}

func main() {
    file, err := "/data/test.txt", 666

    s := log33("File {file} had error {error}", P{"file": file, "error": err})
    fmt.Println(s)
}

func log33(format string, p P) string {
    args, i := make([]string, len(p)*2), 0
    for k, v := range p {
        args[i] = "{" + k + "}"
        args[i+1] = fmt.Sprint(v)
        i += 2
    }
    return strings.NewReplacer(args...).Replace(format)
}

Try it on the Go Playground.

With text/template

Your template solution or proposal is also way too verbose. It can be written as compact as this (error checks omitted):

type P map[string]interface{}

func main() {
    file, err := "/data/test.txt", 666

    log4("File {{.file}} has error {{.error}}", P{"file": file, "error": err})
}

func log4(format string, p P) {
    t := template.Must(template.New("").Parse(format))
    t.Execute(os.Stdout, p)
}

Output (try it on the Go Playground):

File /data/test.txt has error 666

If you want to return the string (instead of printing it to the standard output), you may do it like this (try it on the Go Playground):

func log5(format string, p P) string {
    b := &bytes.Buffer{}
    template.Must(template.New("").Parse(format)).Execute(b, p)
    return b.String()
}

Using explicit argument indices

This was already mentioned in another answer, but to complete it, know that the same explicit argument index may be used arbitrary number of times and thus resulting in the same parameter substituted in multiple times. Read more about this in this question: Replace all variables in Sprintf with same variable

like image 183
icza Avatar answered Sep 20 '22 20:09

icza


I don't know of any easy way of naming the parameters, but you can easily change the order of the arguments, using explicit argument indexes:

From 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. The same notation before a '*' for a width or precision selects the argument index holding the value. After processing a bracketed expression [n], subsequent verbs will use arguments n+1, n+2, etc. unless otherwise directed.

Then you can, ie:

fmt.Printf("File %[2]s had error %[1]s", err, myfile)
like image 30
hlscalon Avatar answered Sep 18 '22 20:09

hlscalon


The parameter can also be a map, so the following function would work if you don't mind parsing every error format every time you use it:

package main

import (
    "bytes"
    "text/template"
    "fmt"
)

func msg(fmt string, args map[string]interface{}) (str string) {
    var msg bytes.Buffer

    tmpl, err := template.New("errmsg").Parse(fmt)

    if err != nil {
        return fmt
    }

    tmpl.Execute(&msg, args)
    return msg.String()
}

func main() {
    fmt.Printf(msg("File {{.File}} has error {{.Error}}\n", map[string]interface{} {
        "File": "abc",
        "Error": "def",
    }))
}

It's still a little wordier than I would have liked, but it's better than some other options, I suppose. You could turn map[string]interface{} into a local type and reduce it further to:

type P map[string]interface{}

fmt.Printf(msg("File {{.File}} has error {{.Error}}\n", P{
        "File": "abc",
        "Error": "def",
    }))
like image 45
Scott Deerwester Avatar answered Sep 18 '22 20:09

Scott Deerwester


Alas, there's no built-in function in Go for string interpolation with named parameters (yet). But you are not the only one suffering out there :) Some packages should exist, for example: https://github.com/imkira/go-interpol . Or, if feeling adventurous, you could write such a helper yourself, as the concept is actually quite simple.

Cheers, Dennis

like image 2
oharlem Avatar answered Sep 22 '22 20:09

oharlem