Convert String to Bool in Golang

Convert string to bool in golang

In the previous blogs, we learnt about conversion between int and string, string and float in Golang. This time we are going to convert String to Bool in Golang.

Learn the above conversions.

Convert String to Bool in Golang Using Strconv ParseBool

func ParseBool(str string) (bool, error)

The Golang Strconv ParseBool Function takes a string and parses it to bool type, and if the parsing is successful it returns the parsed bool else the error is returned.

Example:

fmt.Println(strconv.ParseBool("true"))
fmt.Println(strconv.ParseBool("false"))
fmt.Println(strconv.ParseBool("TRUE"))
fmt.Println(strconv.ParseBool("FALSE"))
fmt.Println(strconv.ParseBool("t"))
fmt.Println(strconv.ParseBool("f"))
fmt.Println(strconv.ParseBool("T"))
fmt.Println(strconv.ParseBool("F"))
fmt.Println(strconv.ParseBool("1"))
fmt.Println(strconv.ParseBool("0"))
fmt.Println(strconv.ParseBool("Go"))
true <nil>
false <nil>
true <nil>
false <nil>
true <nil>
false <nil>
true <nil>
false <nil>
true <nil>
false <nil>
false strconv.ParseBool: parsing "Go": invalid syntax

The Go Strconv ParseBool Function parses the string “true“, “TRUE“, “t“, “1“, “T” to true and “false“,”FALSE“,”f“, “F“,”0” to false.

If the passed string doesn’t parse to bool the function returns an error and the value returned is false.

Learn more about Golang strconv package from the official Documentation.

Tags: ,

Leave a Reply

Your email address will not be published. Required fields are marked *