How to convert Boolean Type to String in Go?
Like most modern languages, Golang includes Boolean as a built-in type. Let's take an example, you may have a variable that contains a boolean value true. In order to convert boolean vale into string type in Golang, you can use the following methods.
FormatBool function
You can use the strconv package's FormatBool() function to convert the boolean into an string value. FormatBool returns "true" or "false" according to the value of b.
Syntax
func FormatBool(b bool) string
Example
package main
import (
"fmt"
"reflect"
"strconv"
)
func main() {
var b bool = true
fmt.Println(reflect.TypeOf(b))
var s string = strconv.FormatBool(true)
fmt.Println(reflect.TypeOf(s))
}
Output
bool
string
fmt.Sprintf() method
Sprintf formats according to a format specifier and returns the resulting string. Here, a is of Interface type hence you can use this method to convert any type to string.
Syntax
func Sprintf(format string, a ...interface{}) string
Example
package main
import (
"fmt"
"reflect"
)
func main() {
b := true
s := fmt.Sprintf("%v", b)
fmt.Println(s)
fmt.Println(reflect.TypeOf(s))
}
Output
true
string
Most Helpful This Week
Golang program for implementation of Linear Search
Golang program to generate number of slices permutations of number entered by user
Example of Interface with Type Embedding and Method Overriding in GO language
Web Application to generate QR code in Golang
Go program to find MX records record of a domain
Example: How to use ReadFull from IO Package in Golang?
Read and Write Fibonacci series to Channel in Golang
Golang program to read XML file into struct
How to convert String to Boolean Data Type Conversion in Go?
How append a slice to an existing slice in Golang?
Most Helpful This Week
Regular expression to validate email addressRegular expression to extract all Non-Alphanumeric Characters from a StringHow to create Map using the make function in Go?How to convert Boolean Type to String in Go?Golang String ConcatenationHow to reads and decodes JSON values from an input stream?Golang download image from given URLHow to count number of repeating words in a given String?How to print string with double quote in Go?How to import structs from another package in Go?