【问题标题】:Go text/template: how to convert bool to int 0/1?Go 文本/模板:如何将 bool 转换为 int 0/1?
【发布时间】:2022-12-28 08:55:09
【问题描述】:

使用 Go text/template 语言,如何将 bool 转换为 int (false=0, true=1)?

这是一个使用我自己的 goproc 工具的示例,该工具允许从命令行执行模板:

$ echo false | goproc -e '{{.}} => <template here>'
false => 0
$ echo true | goproc -e '{{.}} => <template here>'
true => 1

【问题讨论】:

    标签: go go-templates


    【解决方案1】:

    这可能是最简单的:

    digitizeBoolTemplate := "{{if . }}1{{else}}0{{end}}"
    

    https://goplay.tools/snippet/T6EwkKLNmhG

    【讨论】:

      【解决方案2】:

      这是一个 hack:使用 index 内置函数从特制字符串中提取字节值,该字符串分别在位置 5 和 4 包含字节 0 和 1。字符串的长度 "true"/"false" 用作指数值。

      $ echo false | goproc -e '{{.}} =&gt; {{index "....
      猜你喜欢
      • 1970-01-01
      • 2017-02-24
      • 1970-01-01
      • 1970-01-01
      • 2011-12-16
      • 1970-01-01
      • 2015-10-07
      • 2011-05-25
      • 1970-01-01
      相关资源
      最近更新 更多