Próbuję przekonwertować bool
o nazwie isExist
na string
(true
lub false
) za pomocą string(isExist)
, ale to nie działa. Jaki jest idiomatyczny sposób na zrobienie tego w Go?Jak przekonwertować bool na ciąg w Go?
6
A
Odpowiedz
23
użyciu pakietu StrConv
strconv.FormatBool(v)
func FormatBool (b Bool) łańcuch FormatBool zwraca "true" lub "false"
według wartość b
4
możesz użyć strconv.FormatBool
tak:
package main
import "fmt"
import "strconv"
func main() {
isExist := true
str := strconv.FormatBool(isExist)
fmt.Println(str) //true
fmt.Printf("%q\n", str) //"true"
}
lub można użyć fmt.Sprint
takiego:
package main
import "fmt"
func main() {
isExist := true
str := fmt.Sprint(isExist)
fmt.Println(str) //true
fmt.Printf("%q\n", str) //"true"
}
lub pisać jak strconv.FormatBool
:
// FormatBool returns "true" or "false" according to the value of b
func FormatBool(b bool) string {
if b {
return "true"
}
return "false"
}
1
Wystarczy użyć fmt.Sprintf("%v", isExist)
, tak jak w przypadku niemal wszystkich typów .