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

Cas*_*per 45 type-conversion go

我想一个转换bool称为isExist一个string(truefalse使用)string(isExist),但它不工作.在Go中这样做的惯用方法是什么?

Brr*_*rrr 84

使用strconv包

文档

strconv.FormatBool(v)

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


mae*_*ics 9

两个主要选项是:

  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"
  }
}
Run Code Online (Sandbox Code Playgroud)

运行方式:

$ 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
Run Code Online (Sandbox Code Playgroud)


小智 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"
}
Run Code Online (Sandbox Code Playgroud)

或者您可以这样使用fmt.Sprint:

package main

import "fmt"

func main() {
    isExist := true
    str := fmt.Sprint(isExist)
    fmt.Println(str)        //true
    fmt.Printf("%q\n", str) //"true"
}
Run Code Online (Sandbox Code Playgroud)

或写如strconv.FormatBool:

// FormatBool returns "true" or "false" according to the value of b
func FormatBool(b bool) string {
    if b {
        return "true"
    }
    return "false"
}
Run Code Online (Sandbox Code Playgroud)


aki*_*kim 5

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