在 Go 中如何将 bool 转换成字符串?

我试图转换一个称为 isExistboolstring(truefalse)通过使用 string(isExist),但它不工作。围棋中的惯用方法是什么?

134205 次浏览

使用 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"
}

或者你可以这样使用 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"
}

在效率方面没有太多的问题,但是一般性是,只要使用 fmt.Sprintf("%v", isExist),就像您对几乎所有类型一样。

两个主要选择是:

  1. strconv.FormatBool(bool) string
  2. 使用 "%t""%v"格式化程序的 fmt.Sprintf(string, bool) string

请注意,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