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() is a built-in function that takes 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

The strconv.FormatBool() function takes a Boolean value as an argument and returns a string representation.

The reflect.TypeOf() function takes an interface{} type variable as an argument which is “stringValue” in our case, and returns its data type. So, it returned a 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.

We assigned the false boolean value to the variable booleanValue and then passed it as an argument to the fmt.Sprintf() function returns the string representation of that value, which is “false“.

We used the fmt.Printf(“Type : %T \nValue : %v\n\n”, stringValue, stringValue) to print the variable type and value, which are “string” and “false”.

Leave a Comment