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
Modernizing Legacy Applications: Critical Tips for Organizational Upgrades
How to create Slice using Make function in Golang?
GO Program to Check Armstrong Number
Golang program to demonstrates how to encode map data into a JSON string.
How do you catch panic in Golang?
5 Must-Know Blockchain Trends for 2024 and Beyond
Most Helpful This Week
Example: Fields and FieldsFunc from BYTES PackageGet Year, Month, Day, Hour, Min and Second from current date and time.Golang Slice interface and array concatenationHow to Convert string to integer type in Go?Example of Switch Case with Break in For LoopSplit a character string based on change of characterHow to rotate an image?How to append text to a file in Golang?How to check if a string contains a substring in Golang?Regex to extract image name from HTML in Golang