Anuj Verma
Anuj Verma

Reputation: 2859

How to print boolean value in Go?

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

Upvotes: 221

Views: 221270

Answers (6)

Pamela Kelly
Pamela Kelly

Reputation: 54

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)

Upvotes: -1

Hunaphu
Hunaphu

Reputation: 701

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))

Upvotes: 0

ffriend
ffriend

Reputation: 28472

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.

Upvotes: 321

Unico
Unico

Reputation: 687

%t is the answer for you.

package main
import "fmt"

func main() {
   s := true
   fmt.Printf("%t", s)
}

Upvotes: 39

Zombo
Zombo

Reputation: 1

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")
}

Upvotes: 3

Nitin
Nitin

Reputation: 654

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

Upvotes: 24

Related Questions