How to convert a bool to a string in Go?

前端 未结 4 896
萌比男神i
萌比男神i 2020-12-15 02:07

I am trying to convert a bool called isExist to a string (true or false) by using string(isExist)

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-15 02:51

    The two main options are:

    1. strconv.FormatBool(bool) string
    2. fmt.Sprintf(string, bool) string with 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
    

提交回复
热议问题