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
Print index and element or data from Array, Slice and Map
User Defined Function Types in Golang
Get Set and Clear Session in Golang
Encoding and Decoding using json.Marshal and json.Unmarshal
Regular expression to extract date(YYYY-MM-DD) from string
Golang Get current Date and Time in EST, UTC and MST?
Most Helpful This Week
How to create Empty and Nil Slice?Regular expression to validate email addressSimple function with return value in GolangExample to compare Println vs PrintfHow to add Watermark or Merge two image?Sierpinski triangle in Go Programming LanguageSelect single argument from all arguments of variadic functionGet Year, Month, Day, Hour, Min and Second from a specified dateExample: Stack and Caller from RUNTIME packageWhat is GOPATH?