相关疑难解决方法(0)

Go中的Python string.format的等价物?

在Python中,您可以这样做:

"File {file} had error {error}".format(file=myfile, error=err)
Run Code Online (Sandbox Code Playgroud)

或这个:

"File %(file)s had error %(error)s" % {"file": myfile, "error": err}
Run Code Online (Sandbox Code Playgroud)

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

fmt.Sprintf("File %s had error %s", myfile, err)
Run Code Online (Sandbox Code Playgroud)

这不允许你交换格式字符串中的参数顺序,你需要为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)
}
Run Code Online (Sandbox Code Playgroud)

这似乎是一个很长的路要走错误信息.是否有更合理的选项允许我提供独立于订单的字符串参数?

python string go

19
推荐指数
2
解决办法
6214
查看次数

标签 统计

go ×1

python ×1

string ×1