Cookies management by TermsFeed Cookie Consent

🔟 Convert string to bool in Go

introduction strings bool

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

Thank you for being on our site 😊. If you like our tutorials and examples, please consider supporting us with a cup of coffee and we'll turn it into more great Go examples.

Have a great day!

Buy Me A Coffee

🍒 Concatenate strings in Go

Learn the differences between string concatenation methods
introduction strings

🖨️ Convert string to []byte or []byte to string in Go

Learn the difference between a string and a byte slice
introduction strings slice

👯 Remove duplicate spaces from a string in Go

Learn how to remove all redundant whitespaces from a string
introduction strings regex