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
How to find the type of the variable by different ways in Golang?
How to blur an image in Golang?
How to check string contains uppercase lowercase character in Golang?
How to get Dimensions of an image type jpg jpeg png or gif ?
Split a string at uppercase letters using regular expression in Golang
Get current date and time in various format in golang
Most Helpful This Week
How to get first and last element of slice in Golang? How to check if a string contains a substring in Golang?How to read/write from/to file in Golang?Example: Fields and FieldsFunc from BYTES PackageWhat is GOPATH?Find capacity of Channel, Pointer and SliceHow to include and execute HTML template?URL parser in GolangHow to kill execution of goroutine?Closures Functions in Golang