如何在 Go 中将布尔值转换为字符串?

新手上路,请多包涵

I am trying to convert a bool called isExist to a string ( true or false ) by using string(isExist) 但它不起作用。在 Go 中执行此操作的惯用方法是什么?

原文由 Casper 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 457
2 个回答

使用 strconv 包

文档

strconv.FormatBool(v)

func FormatBool(b bool) string FormatBool 返回“true”或“false”

根据 b 的值

原文由 Brrrr 发布,翻译遵循 CC BY-SA 3.0 许可协议

两个主要选项是:

  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

原文由 maerics 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题