I am trying to convert a bool called isExist to a string (true or false) by using string(isExist) but it does not work. What is the idiomatic way to do this in Go?
            Asked
            
        
        
            Active
            
        
            Viewed 1.6e+01k times
        
    166
            
            
         
    
    
        Casper
        
- 4,435
- 10
- 41
- 72
- 
                    3`strconv.FormatBool(t)` to set `true` to “true”. `strconv.ParseBool("true")` to set “true” to `true`. See https://stackoverflow.com/a/62740786/12817546. – Jul 09 '20 at 10:18
4 Answers
45
            
            
        The two main options are:
- strconv.FormatBool(bool) string
- fmt.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
 
    
    
        maerics
        
- 151,642
- 46
- 269
- 291
13
            
            
        In efficiency is not too much of an issue, but genericity is, just use fmt.Sprintf("%v", isExist), as you would for almost all the types.
 
    
    
        akim
        
- 8,255
- 3
- 44
- 60
10
            
            
        you may use strconv.FormatBool like this:  
package main
import "fmt"
import "strconv"
func main() {
    isExist := true
    str := strconv.FormatBool(isExist)
    fmt.Println(str)        //true
    fmt.Printf("%q\n", str) //"true"
}
or you may use fmt.Sprint like this:  
package main
import "fmt"
func main() {
    isExist := true
    str := fmt.Sprint(isExist)
    fmt.Println(str)        //true
    fmt.Printf("%q\n", str) //"true"
}
or write like strconv.FormatBool:  
// FormatBool returns "true" or "false" according to the value of b
func FormatBool(b bool) string {
    if b {
        return "true"
    }
    return "false"
}
