To convert a string to a bool in Go, use strconv.ParseBool()
function from the strconv
package. It takes one of the accepted string values: "1"
, "t"
, "T"
, "TRUE"
, "true"
, "True"
, "0"
, "f"
, "F"
, "FALSE"
, "false"
, "False"
and converts it to the equivalent boolean value: true
or false
. For any other string, the function returns an error.
package main
import (
"fmt"
"log"
"strconv"
)
func main() {
var boolValues = []string{
"1",
"t",
"T",
"TRUE",
"true",
"True",
"0",
"f",
"F",
"FALSE",
"false",
"False",
}
for _, v := range boolValues {
boolValue, err := strconv.ParseBool(v)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s: %t\n", v, boolValue)
}
}
Output:
1: true
t: true
T: true
TRUE: true
true: true
True: true
0: false
f: false
F: false
FALSE: false
false: false
False: false