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
.
With FormatBool
we can get a string
from a bool
. The two methods (ParseBool
and FormatBool
) are often used together in the same programs.
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
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.
strconv.ParseBool
performs are we expect it to—true-meaning strings are converted to true.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 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."
For converting types, strconv
is essential in Go. We use ParseBool
and FormatBool
to convert strings to bools (parsing them) and bools to strings.