use the strconv package
docs
strconv.FormatBool(v)
Answer from Brrrr on Stack Overflowfunc FormatBool(b bool) string FormatBool returns "true" or "false"
according to the value of b
type conversion - How to convert a bool to a string in Go? - Stack Overflow
Parse a boolean value represented by string logically
go - Parse parameter to bool or just use string in switch statement - Stack Overflow
types - Is there a way to convert integers to bools in go or vice versa? - Stack Overflow
use the strconv package
docs
strconv.FormatBool(v)
func FormatBool(b bool) string FormatBool returns "true" or "false"
according to the value of b
The two main options are:
strconv.FormatBool(bool) stringfmt.Sprintf(string, bool) stringwith the"%t"or"%v"formatters.
Note that strconv.FormatBool(...) is considerably faster than fmt.Sprintf(...) as demonstrated by the following benchmarks:
func Benchmark_StrconvFormatBool(b *testing.B) {
for i := 0; i < b.N; i++ {
strconv.FormatBool(true) // => "true"
strconv.FormatBool(false) // => "false"
}
}
func Benchmark_FmtSprintfT(b *testing.B) {
for i := 0; i < b.N; i++ {
fmt.Sprintf("%t", true) // => "true"
fmt.Sprintf("%t", false) // => "false"
}
}
func Benchmark_FmtSprintfV(b *testing.B) {
for i := 0; i < b.N; i++ {
fmt.Sprintf("%v", true) // => "true"
fmt.Sprintf("%v", false) // => "false"
}
}
Run as:
$ go test -bench=. ./boolstr_test.go
goos: darwin
goarch: amd64
Benchmark_StrconvFormatBool-8 2000000000 0.30 ns/op
Benchmark_FmtSprintfT-8 10000000 130 ns/op
Benchmark_FmtSprintfV-8 10000000 130 ns/op
PASS
ok command-line-arguments 3.531s
Int to bool is easy, just x != 0 will do the trick. To go the other way, since Go doesn't support a ternary operator, you'd have to do:
var x int
if b {
x = 1
} else {
x = 0
}
You could of course put this in a function:
func Btoi(b bool) int {
if b {
return 1
}
return 0
}
There are so many possible boolean interpretations of integers, none of them necessarily natural, that it sort of makes sense to have to say what you mean.
In my experience (YMMV), you don't have to do this often if you're writing good code. It's appealing sometimes to be able to write a mathematical expression based on a boolean, but your maintainers will thank you for avoiding it.
Here's a trick to convert from int to bool:
x := 0
newBool := x != 0 // returns false
where x is the int variable you want to convert from.
The simplest way would be to use the strconv.ParseBool package. Like this:
func (b *NullBool) UnmarshalJSON(data []byte) error {
var err error
b.Bool, err = strconv.ParseBool(string(data))
b.Valid = (err == nil)
return err
}
You can use the json module almost directly.
func (nb *NullBool) UnmarshalJSON(data []byte) error {
err := json.Unmarshal(data, &nb.Bool)
nb.Valid = (err == nil)
return err
}