Home > Blockchain >  Go text/template: how to convert bool to int 0/1?
Go text/template: how to convert bool to int 0/1?

Time:11-19

With Go text/template language, how can I convert a bool to an int (false=0, true=1)?

Here is an example using the goproc tool that allows to execute template from the command line:

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

CodePudding user response:

Here is a hack: use the index built-in function to extract byte values from a specially crafted string that contains bytes 0 and 1 respectively at positions 5 and 4. The lengths of strings "true"/"false" are used as the index value.

$ echo false | goproc -e '{{.}} => {{index "....\001\000" (len (print .))}}{{"\n"}}'
false => 0
$ echo true | goproc -e '{{.}} => {{index "....\001\000" (len (print .))}}{{"\n"}}'
true => 1

CodePudding user response:

This is probably the simplest:

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

https://goplay.tools/snippet/T6EwkKLNmhG

  • Related