Home
Search
Golang Convert String to Bool: strconv.ParseBoolUse the strconv.ParseBool func to convert a string into a bool. Call FormatBool to convert from a bool to a string.
Convert string, bool. In Go we use the strconv package to convert types like bool and strings. We can use ParseBool to get a bool from a string.
Format info. With FormatBool we can get a string from a bool. The two methods (ParseBool and FormatBool) are often used together in the same programs.
ParseInt
Input and output. Suppose we have the string "true," and want the boolean true. And meanwhile, the string "false" must be parsed as false.
Required output:
"true" -> true "false" -> false
An example. To begin, we introduce a string slice of many versions of "true" and "false" strings. These should evaluate to true or false when we invoke ParseBool upon them.
Result We see that the strconv.ParseBool performs are we expect it to—true-meaning strings are converted to true.
FormatBool For FormatBool, we go from a bool (true or false) to a string like "true" or "false." This helps whenever we need a string.
Golang program that uses strconv.ParseBool
package main import ( "fmt" "strconv" ) func main() { tests := []string{"1", "t", "T", "TRUE", "true", "True", "0", "f", "F", "FALSE", "false", "False"} // Loop over strings in string slice. for _, item := range(tests) { // Convert string to bool with ParseBool. result, _ := strconv.ParseBool(item) // Convert bool to string with FormatBool. fmt.Println(item + "->" + strconv.FormatBool(result)) } }
1->true t->true T->true TRUE->true true->true True->true 0->false f->false F->false FALSE->false false->false False->false
Some notes. Some languages do not provide support for variants of strings that mean true or false. But in Go we have support for many strings like "t" and "1," not just "true."
A summary. For converting types, strconv is essential in Go. We use ParseBool and FormatBool to convert strings to bools (parsing them) and bools to strings.
Home
© 2007-2021 sam allen.
see site info on the changelog.