如何在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
    。看见