Converting string to bool can be done using the strconv.ParseBool
method. It tries to return a boolean value from a string. It accepts the strings in the following format
// True string values
1, t, T, TRUE, true, True
// False string values
0, f, F, FALSE, false, False
Anything else apart from these value will throw an error when using the strconv.ParseBool
method.
// stringVal can be set to any one of the above valid values.
value, err := strconv.ParseBool(stringVal)
package main
import (
"fmt"
"strconv"
)
func main() {
// Success conversion with no error
boolString := "True"
boolVal, err := strconv.ParseBool(boolString)
if err != nil {
fmt.Println("Error in conversion", err)
} else {
fmt.Println("Converted Boolean value - ", boolVal)
}
// Error conversion
boolErrString := "Abcd"
boolErrVal, err := strconv.ParseBool(boolErrString)
if err != nil {
fmt.Println("Error in conversion", err)
} else {
fmt.Println("Converted Boolean value - ", boolErrVal)
}
}
Steps to convert
strconv.ParseBool
method to get a value or errorYou can check the official documentation for more details - https://pkg.go.dev/strconv#ParseBool
Sriram is a content creator focused on providing quality content which provides value for the readers. He believe is constant learning and sharing those learning with the group. He is working as a lead developer and bulk of his experience is in working with multiple javascript frameworks such as Angular, React, Svelte. He is passionate about open source technologies and on his free time loves to develop games.
We will reach out when exciting new posts are available. We won’t send you spam. Unsubscribe at any time.