我正在尝试将名为isExist
的bool
转换为string
(true或false),使用string(isExist)
,但无法正常工作。在Go中,有什么惯用的方法可以做到这一点?
我正在尝试将名为isExist
的bool
转换为string
(true或false),使用string(isExist)
,但无法正常工作。在Go中,有什么惯用的方法可以做到这一点?
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
fmt.Sprintf("%v", isExist)
即可。你可以像这样使用 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
。请参阅https://dev59.com/OVwZ5IYBdhLWcg3waPvX#62740786。 - user12817546