を使用して、bool呼び出さisExistれたものをstring(trueまたはfalse)に変換しようとしてstring(isExist)いますが、機能しません。Goでこれを行う慣用的な方法は何ですか?
回答:
2つの主なオプションは次のとおりです。
strconv.FormatBool(bool) stringfmt.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
あなたは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を参照してください。