How to Convert Bool to String in Go

To convert a boolean to a string in Go, you can use the “strconv.FormatBool()” or “fmt.Sprint()” function.

Method 1: Using strconv.FormatBool() function

You can use the “strconv.FormatBool()” function to convert a boolean to a string. The strconv.FormatBool() function accepts a Boolean value as an argument and returns a string representation of that value.

Syntax

func FormatBool(x bool) string

Parameters

The FormatBool() function takes “x” as a single required parameter of the bool type.

Example

package main

import (
  "fmt"
  "reflect"
  "strconv"
)

func main() {
  booleanValue := true

 // Convert Boolean to string
  stringValue := strconv.FormatBool(booleanValue)

 // Print result
  fmt.Println(stringValue)

 // Print the data type of a variable 
 fmt.Println("The data type of string value is: ", reflect.TypeOf(stringValue))
}

Output

true
The data type of string value is: string

Method 2: Using fmt.Sprint() function

Another approach is to use the fmt.Sprintf() function converts a boolean value to a string in Go. The fmt.Sprintf() represents the string by formatting according to a format specifier.

Syntax

func Sprintf(format string, a ...interface{}) string

Parameters

format string: It includes some verbs along with some strings.

a …interface{}: It is the specified constant variable.

Example

package main

import (
  "fmt"
)

func main() {
  booleanValue := false

  stringValue := fmt.Sprintf("%v", booleanValue)
  fmt.Printf("Type : %T \nValue : %v\n\n", stringValue, stringValue)

  boolValue := true
  strValue := fmt.Sprintf("%v", boolValue)
  fmt.Printf("Type : %T \nValue : %v\n", strValue, strValue)
}

Output

Type : string
Value : false

Type : string
Value : true

The format string is “%v”, a general format representing the value in a default format.

That’s it!

Related posts

Go string to bool

Go rune to string

Go Uint16 to String

Go interface to string

Go time to string