相当于Go中的Python string.format?

2024-04-24 14:56:20 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python中,您可以执行以下操作:

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

或者这个:

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

在Go中,最简单的选择是:

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

这不允许您交换格式字符串中参数的顺序,您需要对I18N执行此操作。Go是否有template包,它需要如下内容:

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)
}

对于一条错误消息来说,这似乎是一段很长的路要走。是否有一个更合理的选项允许我提供与顺序无关的字符串参数?


Tags: 字符串go参数bytes顺序maintemplatemsg
3条回答

我不知道任何命名参数的简单方法,但是可以使用显式参数索引轻松更改参数的顺序:

来自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.

那你就可以了

fmt.Printf("File %[2]s had error %[1]s", err, myfile)

strings.Replacer

使用^{},实现愿望的格式化程序非常简单和紧凑。

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))
}

输出(在Go Playground上尝试):

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

我们可以通过在log()函数中自动将括号添加到参数名中,使其更易于使用:

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))
}

输出(在Go Playground上尝试):

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

是的,您可以说它只接受string参数值。这是真的。如果再提高一点,就不会是这样了:

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))
}

输出(在Go Playground上尝试):

File /data/test.txt had error 666

接受参数作为map[string]interface{}并返回结果作为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)
}

Go Playground上试试。

text/template

你的模板解决方案或建议也太冗长了。它可以这样写(省略错误检查):

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)
}

输出(在Go Playground上尝试):

File /data/test.txt has error 666

如果要返回string(而不是打印到标准输出),可以这样做(在Go Playground上尝试):

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

使用显式参数索引

这已经在另一个答案中提到了,但是要完成它,要知道同一个显式参数索引可以被任意次数使用,从而导致同一个参数被多次替换。在这个问题中阅读更多关于这个的信息:Replace all variables in Sprintf with same variable

参数也可以是一个映射,因此如果您不介意每次使用时都解析每个错误格式,则以下函数将起作用:

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",
    }))
}

它仍然比我想要的要多一些,但是我想它比其他的选择要好。您可以将map[string]interface{}转换为本地类型,并进一步将其减少为:

type P map[string]interface{}

fmt.Printf(msg("File {{.File}} has error {{.Error}}\n", P{
        "File": "abc",
        "Error": "def",
    }))

相关问题 更多 >