As we have %d
for int. What is the format specifier for boolean values?
How to print boolean value in Go?
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.
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 %t
is the answer for you.
package main
import "fmt"
func main() {
s := true
fmt.Printf("%t", s)
}
Use %t
to format a boolean as true
or false
.
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 –
Incoordination
this answer shows what will be in the output. Super! –
Conchoid
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")
}
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))
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)
© 2022 - 2025 — McMap. All rights reserved.
strconv.FormatBool(b)
is much faster in case speed is important. – Overshadow