如何在Go中将布尔转换为字符串?
我试图使用如何在Go中将布尔转换为字符串?,go,type-conversion,Go,Type Conversion,我试图使用string(isExist)将名为isExist的bool转换为string(true或false),但它不起作用。Go中的惯用方法是什么?使用strconv包 strconv.FormatBool(v) func FormatBool(b bool)字符串FormatBool返回“true”或“false” 根据b的值 您可以像这样使用strconv.FormatBool: package main import "fmt" import "strconv" func mai
string(isExist)
将名为isExist
的bool
转换为string
(true
或false
),但它不起作用。Go中的惯用方法是什么?使用strconv包
strconv.FormatBool(v)
func FormatBool(b bool)字符串FormatBool返回“true”或“false”根据b的值
您可以像这样使用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"
}
package main
import "fmt"
func main() {
isExist := true
str := fmt.Sprint(isExist)
fmt.Println(str) //true
fmt.Printf("%q\n", str) //"true"
}
或者您可以像这样使用fmt.Sprint
:
package main
import "fmt"
import "strconv"
func main() {
isExist := true
str := strconv.FormatBool(isExist)
fmt.Println(str) //true
fmt.Printf("%q\n", str) //"true"
}
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"
}
只需使用
fmt.Sprintf(“%v”,isExist)
,几乎所有类型都可以使用。两个主要选项是:
%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"
}
}
strconv.FormatBool(t)
设置true
为“true”strconv.ParseBool(“true”)
将“true”设置为true
。看见