How to print boolean value in Go?
Asked Answered
G

6

204

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

Gittle answered 14/8, 2011 at 21:9 Comment(2)
Try a code example: play.golang.org/p/RDGQEryOLPCrelin
Note that strconv.FormatBool(b) is much faster in case speed is important.Overshadow
T
292

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.

Tungus answered 14/8, 2011 at 21:14 Comment(4)
Also note that the %v format will print a reasonable default string for any value.Sibilla
If I try to take input a boolean value; any value starting from 't' is true and any other value is false.Gittle
package main import fmt "fmt" func main(){ var flag bool fmt.Scanf("%t",&flag) fmt.Printf("%t",flag) }Gittle
@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 code and check results with different inputs.Tungus
H
36

%t is the answer for you.

package main
import "fmt"

func main() {
   s := true
   fmt.Printf("%t", s)
}
Hannis answered 8/6, 2021 at 3:9 Comment(0)
E
24

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

Emptyheaded answered 6/7, 2020 at 7:43 Comment(2)
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 containsIncoordination
this answer shows what will be in the output. Super!Conchoid
M
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")
}
Malefactor answered 27/3, 2021 at 2:19 Comment(0)
G
0

In my case, I need the bool to be 0/1. Then, this works.

func b2int(b bool) int8 {
    if b { return 1 }
    return 0
}
fmt.Sprintf("%d", b2int(b))
Geodynamics answered 24/1, 2024 at 23:27 Comment(0)
L
-1

Expanding on the above answers to include types booleans.

To print standard bool use %t as mentioned above:

isItTrue = true

fmt.Printf("Is it true? %t", isItTrue)

To print typed bools use %v and dereference the variable:

var isItTrue bool = true

fmt.Printf("Is it true? %v", *isItTrue)
Leastwise answered 25/3, 2024 at 15:49 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.