187

As we have %d for int. What is the format specifier for boolean values?

Rene Knop
  • 1,788
  • 3
  • 15
  • 27
Anuj Verma
  • 2,519
  • 3
  • 17
  • 23
  • Try a code example: https://play.golang.org/p/RDGQEryOLP – KingRider Jul 20 '17 at 14:18
  • 3
    Note that [`strconv.FormatBool(b)` is *much* faster](https://stackoverflow.com/questions/38552803/how-to-convert-a-bool-to-a-string-in-go) in case speed is important. – maerics Nov 11 '18 at 19:04

4 Answers4

262

If you use fmt package, you need %t format syntax, which will print true or false for boolean variables.

See package's reference for details.

Amin Shojaei
  • 5,451
  • 2
  • 38
  • 46
ffriend
  • 27,562
  • 13
  • 91
  • 132
  • 37
    Also note that the %v format will print a reasonable default string for any value. – Evan Shaw Aug 14 '11 at 21:43
  • If I try to take input a boolean value; any value starting from 't' is true and any other value is false. – Anuj Verma Aug 21 '11 at 17:43
  • package main import fmt "fmt" func main(){ var flag bool fmt.Scanf("%t",&flag) fmt.Printf("%t",flag) } – Anuj Verma Aug 22 '11 at 14:30
  • 1
    @Anuj Verma: When scanning input, `fmt.Scanf` had to deal somehow with any string you pass it. It can read values `true` and `false` correctly, and that's its main purpose. When it doesn't see neither `true`, nor `false` in the input, it goes another way: it takes only first character and returns `true` if it is 't' or `false` if it is anything else, i.g. not-'t'. Note, that the rest of the input is still available for scanning with other options. For example, try [such](http://pastebin.com/2EqrRFJg) code and check results with different inputs. – ffriend Aug 23 '11 at 16:08
33

%t is the answer for you.

package main
import "fmt"

func main() {
   s := true
   fmt.Printf("%t", s)
}
Unico
  • 607
  • 5
  • 6
23

Use %t to format a boolean as true or false.

Digvijay S
  • 2,665
  • 1
  • 9
  • 21
Nitin
  • 541
  • 4
  • 5
  • 5
    This is a the same answer, but shortened of the accepted one, remember that if you want to answer you should check when you can add something the post does not contains – xKobalt Jul 06 '20 at 08:16
3

Some other options:

package main
import "strconv"

func main() {
   s := strconv.FormatBool(true)
   println(s == "true")
}
package main
import "fmt"

func main() {
   var s string
   // example 1
   s = fmt.Sprint(true)
   println(s == "true")
   // example 2
   s = fmt.Sprintf("%v", true)
   println(s == "true")
}
Zombo
  • 1
  • 62
  • 391
  • 407