Estoy tratando de convertir una boolllamada isExista string( trueo false) usando string(isExist)pero no funciona. ¿Cuál es la forma idiomática de hacer esto en Go?
                    
                        go
                                type-conversion
                                
                    
                    
                        Casper
fuente
                
                fuente

strconv.FormatBool(t)para establecertrueen "verdadero".strconv.ParseBool("true")para establecer "verdadero"true. Consulte stackoverflow.com/a/62740786/12817546 .Respuestas:
usa el paquete strconv
docs
strconv.FormatBool(v)fuente
Las dos opciones principales son:
strconv.FormatBool(bool) stringfmt.Sprintf(string, bool) stringcon los formateadores"%t"o"%v".Tenga en cuenta que
strconv.FormatBool(...)es considerablemente más rápido que lofmt.Sprintf(...)que demuestran los siguientes puntos de referencia: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" } }Correr como:
$ 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.531sfuente
puede usar
strconv.FormatBoolasí:package main import "fmt" import "strconv" func main() { isExist := true str := strconv.FormatBool(isExist) fmt.Println(str) //true fmt.Printf("%q\n", str) //"true" }o puede usar
fmt.Sprintasí:package main import "fmt" func main() { isExist := true str := fmt.Sprint(isExist) fmt.Println(str) //true fmt.Printf("%q\n", str) //"true" }o escribe como
strconv.FormatBool:// FormatBool returns "true" or "false" according to the value of b func FormatBool(b bool) string { if b { return "true" } return "false" }fuente
Úselo
fmt.Sprintf("%v", isExist), como lo haría con casi todos los tipos.fuente