go: 字符串format时使用命名参数(占位符) 在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了。 来自 大脸猪 写于 2021-12-11 18:39 -- 更新于2021-12-13 19:59 -- 0 条评论