With strings.Replacer
Using strings.Replacer https://golang.org/pkg/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))
}
输出(尝试一下去游乐场 https://play.golang.org/p/sDVi-3NUiw):
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))
}
输出(尝试一下去游乐场 https://play.golang.org/p/3Odo_LmM6c):
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))
}
输出(尝试一下去游乐场 https://play.golang.org/p/0KtRjDIFTN):
File /data/test.txt had error 666
其变体接受 params 作为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)
}
尝试一下去游乐场 https://play.golang.org/p/i9XUTN9V3m.
With 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)
}
输出(尝试一下去游乐场 https://play.golang.org/p/D-hoAeCakq):
File /data/test.txt has error 666
如果您想退回string
(而不是将其打印到标准输出),您可以这样做(在去游乐场 https://play.golang.org/p/L9L9OerQYZ):
func log5(format string, p P) string {
b := &bytes.Buffer{}
template.Must(template.New("").Parse(format)).Execute(b, p)
return b.String()
}
使用显式参数索引
这已经在另一个答案中提到过,但要完成它,请知道相同的显式参数索引可以使用任意次数,从而导致相同的参数被多次替换。在这个问题中阅读更多相关信息:将 Sprintf 中的所有变量替换为相同的变量 https://stackoverflow.com/questions/37001449/replace-all-variables-in-sprintf-with-same-variable