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

166

我正在尝试将名为isExistbool转换为string(true或false),使用string(isExist),但无法正常工作。在Go中,有什么惯用的方法可以做到这一点?


3
strconv.FormatBool(t)转换为将true设置为字符串"true"。 将strconv.ParseBool("true")转换为将字符串"true"设置为布尔值true。请参阅https://dev59.com/OVwZ5IYBdhLWcg3waPvX#62740786。 - user12817546
4个回答

276

使用strconv包

文档

strconv.FormatBool(v)

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


46
两种主要选项如下:
  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

13
在效率不是太大问题的情况下,泛型性是个问题。只需像对待几乎所有类型一样使用fmt.Sprintf("%v", isExist)即可。

10

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接