我想转换一个bool
叫isExist
到string
(true
或false
使用),string(isExist)
但它不能做的工作。Go中惯用的方式是什么?
Answers:
两个主要选项是:
请注意,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
您可以这样使用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"
}
strconv.FormatBool(t)
设置true
为“ true”。strconv.ParseBool("true")
将“ true”设置为true
。请参阅stackoverflow.com/a/62740786/12817546。