How to convert a Boolean to a string in Golang
A Boolean can be converted to a string in Golang using the following:
- The
FormatBoolfunction within thestrconvpackage. - The
Sprintffunction within thefmtpackage.
FormatBool
The FormatBool function accepts a boolean value as a parameter and converts it into a string.
The code snippet below shows how to convert a Boolean to a string using the FormatBool function:
package mainimport ("fmt""strconv")func main() {boolVal := truestrVal := strconv.FormatBool(boolVal)fmt.Printf("Type of strVal: %T\n", strVal)fmt.Printf("Type of boolVal: %T\n", boolVal)fmt.Println()fmt.Printf("Value of strVal: %v\n", strVal)fmt.Printf("Value of boolVal: %v", boolVal)}
Explanation
We have declared a boolean variable boolVal and initialized it to true (line 9). Then, we have converted it to string using FormatBool function and stored the result in the strVal variable (line 10).
At last, we have output the type and value of the strVal and the boolVal on the console (line 11-15).
Sprintf
The code snippet below shows us how to convert a Boolean to a string, using the Sprintf function:
package mainimport ("fmt")func main() {boolVal := falsestrVal := fmt.Sprintf("%v", boolVal)fmt.Printf("Type of strVal: %T\n", strVal)fmt.Printf("Type of boolVal: %T\n", boolVal)fmt.Println()fmt.Printf("Value of strVal: %v\n", strVal)fmt.Printf("Value of boolVal: %v", boolVal)}
Explanation
We have declared a boolean variable boolVal and initialized it to false (line 8). Then, we have converted it to string using the Sprintf function and stored the result in the strVal variable (line 9).
At last, we have output the type and value of the strVal and the boolVal on the console (line 10-14).