Cas*_*per 45 type-conversion go
我想一个转换bool
称为isExist
一个string
(true
或false
使用)string(isExist)
,但它不工作.在Go中这样做的惯用方法是什么?
两个主要选项是:
请注意,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"
}
}
Run Code Online (Sandbox Code Playgroud)
运行方式:
$ 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
Run Code Online (Sandbox Code Playgroud)
小智 6
你可以这样使用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"
}
Run Code Online (Sandbox Code Playgroud)
或者您可以这样使用fmt.Sprint
:
package main
import "fmt"
func main() {
isExist := true
str := fmt.Sprint(isExist)
fmt.Println(str) //true
fmt.Printf("%q\n", str) //"true"
}
Run Code Online (Sandbox Code Playgroud)
或写如strconv.FormatBool
:
// FormatBool returns "true" or "false" according to the value of b
func FormatBool(b bool) string {
if b {
return "true"
}
return "false"
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
36003 次 |
最近记录: |