在python中,可以在format的时候对占位符命名。这在参数非常多的时候,且顺序不定时非常明确。 例如:
print("用户:{name}".format(name="superpig"))
但go的fmt.Sprintf()
就没这么好用啦。
解决方法很简单,使用go templates
。
直接上代码。
package tpfmt
import (
"strings"
"text/template"
)
type FormatTp struct {
tp *template.Template
}
// Exec 传入map填充预定的模板
func (f FormatTp) Exec(args map[string]interface{}) string {
s := new(strings.Builder)
err := f.tp.Execute(s, args)
if err != nil {
// 放心吧,这里不可能触发的,除非手贱:)
panic(err)
}
return s.String()
}
/* Format 自定义命名format,严格按照 {{.CUSTOMNAME}} 作为预定参数,不要写任何其它的template语法
usage:
s = Format("{{.name}} hello.").Exec(map[string]interface{}{
"name": "superpig",
}) // s: superpig hello.
*/
func Format(fmt string) FormatTp {
var err error
temp, err := template.New("").Parse(fmt)
if err != nil {
// 放心吧,这里不可能触发的,除非手贱:)
panic(err)
}
return FormatTp{tp: temp}
}
现在,使用封装的Format函数,就能很方便的对字符串自定义format了。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有