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

时间:2016-07-24 13:56:33

标签: go type-conversion

我正在尝试使用bool将名为isExist的{​​{1}}转换为stringtruefalse},但确实如此不行。在Go中这样做的惯用方法是什么?

4 个答案:

答案 0 :(得分:60)

使用strconv包

docs

strconv.FormatBool(v)

  

func FormatBool(b bool)string FormatBool返回" true"或"假"
  根据b的值

答案 1 :(得分:6)

您可以像这样使用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"
}

答案 2 :(得分:3)

只需使用fmt.Sprintf("%v", isExist),就像使用几乎所有类型一样。

答案 3 :(得分:2)

两个主要选项是:

  1. strconv.FormatBool(bool) string
  2. fmt.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