如何在Go中将布尔值转换为字符串?


Answers:


150

使用strconv包

docs

strconv.FormatBool(v)

func FormatBool(b bool)字符串FormatBool
根据b的值返回“ true”或“ false”


20

两个主要选项是:

  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

8

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

8

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

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.