🔟 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

🖨️ 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

📰 String padding in Go

Learn how to print aligned strings padded with spaces
introduction strings format