Convert String to Bool: strconv.ParseBool
This page was last reviewed on May 24, 2021.
Dot Net Perls
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.
Input and output. Suppose we have the string "true," and want the boolean true. And meanwhile, the string "false" must be parsed as false.
"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.
Detail For FormatBool, we go from a bool (true or false) to a string like "true" or "false." This helps whenever we need a string.
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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on May 24, 2021 (edit link).
© 2007-2024 Sam Allen.