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 许可协议
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 许可协议
两个主要选项是:
strconv.FormatBool(bool) string
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 许可协议
7 回答5.3k 阅读
6 回答6.8k 阅读✓ 已解决
4 回答2.3k 阅读
1 回答3.3k 阅读
2 回答2.2k 阅读
1 回答2.1k 阅读
1 回答1.5k 阅读
使用 strconv 包
文档
strconv.FormatBool(v)