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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on May 24, 2021 (edit link).