前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >go: 字符串format时使用命名参数(占位符)

go: 字符串format时使用命名参数(占位符)

作者头像
超级大猪
发布2021-12-24 14:29:07
2.4K0
发布2021-12-24 14:29:07
举报
文章被收录于专栏:大猪的笔记大猪的笔记

在python中,可以在format的时候对占位符命名。这在参数非常多的时候,且顺序不定时非常明确。 例如:

代码语言:javascript
复制
print("用户:{name}".format(name="superpig"))

但go的fmt.Sprintf()就没这么好用啦。

解决方法很简单,使用go templates

直接上代码。

代码语言:javascript
复制
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 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档