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
Struct Instantiation Using Pointer Address Operator
How do you handle HTTP redirects in Go?
How do you send an HTTP PATCH request in Go?
GO Program to Generate Multiplication Table
Defining a type that satisfies an interface in Go Programming Language
Find odd and even numbers using goroutines and channels
Converting Int data type to Float in Go
How to set timeout for http.Get() requests in Golang?
Golang program for implementation of Pancake Sort
Top 20 Most Popular Cryptocurrencies To Watch In 2024
Most Helpful This Week
How to read names of all files and folders in current directory?How can we reverse a simple string in Go?Closures Functions in GolangReplace numbers by zero from stringExample to handle GET and POST request in GolangRegular expression to extract all Non-Alphanumeric Characters from a StringHow to convert Go struct to JSON?How to Remove duplicate values from Slice?How to create Empty and Nil Slice?Get current date and time in various format in golang