【问题标题】:How to convert a bool to a string in Go?如何在 Go 中将布尔值转换为字符串?
【发布时间】:2016-11-27 21:55:03
【问题描述】:

我正在尝试使用string(isExist) 将名为isExistbool 转换为stringtruefalse),但它不起作用。在 Go 中执行此操作的惯用方式是什么?

【问题讨论】:

标签: go type-conversion


【解决方案1】:

使用 strconv 包

docs

strconv.FormatBool(v)

func FormatBool(b bool) 字符串 FormatBool 返回“真”或“假”
根据b的值

【讨论】:

    【解决方案2】:

    两个主要选项是:

    1. strconv.FormatBool(bool) string
    2. fmt.Sprintf(string, bool) string"%t""%v" 格式化程序。

    请注意,strconv.FormatBool(...)fmt.Sprintf(...)相当快,如下基准所示:

    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"
      }
    }
    

    运行方式:

    $ 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
    

    【讨论】:

      【解决方案3】:

      效率不是太大问题,但通用性是,只需使用fmt.Sprintf("%v", isExist),就像对几乎所有类型一样。

      【讨论】:

        【解决方案4】:

        你可以像这样使用strconv.FormatBool

        package main
        
        import "fmt"
        import "strconv"
        
        func main() {
            isExist := true
            str := strconv.FormatBool(isExist)
            fmt.Println(str)        //true
            fmt.Printf("%q\n", str) //"true"
        }
        

        或者你可以像这样使用fmt.Sprint

        package main
        
        import "fmt"
        
        func main() {
            isExist := true
            str := fmt.Sprint(isExist)
            fmt.Println(str)        //true
            fmt.Printf("%q\n", str) //"true"
        }
        

        或者像strconv.FormatBool这样写:

        // FormatBool returns "true" or "false" according to the value of b
        func FormatBool(b bool) string {
            if b {
                return "true"
            }
            return "false"
        }
        

        【讨论】:

          猜你喜欢
          • 2011-02-17
          • 2012-04-02
          • 2021-02-23
          • 1970-01-01
          • 1970-01-01
          • 2018-09-07
          • 1970-01-01
          • 2010-09-20
          相关资源
          最近更新 更多