How to Convert a Bool to a String in Go

Created
Modified

Using strconv.FormatBool Function

The strconv.FormatBool() function returns "true" or "false" according to the value of b. For example,

package main

import (
  "fmt"
  "strconv"
)

func main() {
  b := true
  s := strconv.FormatBool(b)
  fmt.Printf("%q\n", s)
}
"true"

Using fmt.Sprintf Function

The fmt.Sprintf() function formats according to a format specifier and returns the resulting string. You can use fmt.Sprintf() with the "%t" or "%v" formatters.

See the following example:

package main

import (
  "fmt"
)

func main() {
  b := true

  s := fmt.Sprintf("%t", b)
  fmt.Printf("%q\n", s)

  s = fmt.Sprintf("%v", b)
  fmt.Printf("%q\n", s)
}
"true"
"true"

Related Tags