boolean Archives - Welcome To Golang By Example https://vikasboss.github.io/tag/boolean/ Sun, 23 Feb 2020 08:19:08 +0000 en-US hourly 1 https://wordpress.org/?v=6.8.1 https://i0.wp.com/golangbyexamples.com/wp-content/uploads/2021/05/cropped-go_border-1.png?fit=32%2C32&ssl=1 boolean Archives - Welcome To Golang By Example https://vikasboss.github.io/tag/boolean/ 32 32 159787465 Parse a bool or Check if given string is a bool in Go (Golang) https://vikasboss.github.io/check-string-bool-golang/ https://vikasboss.github.io/check-string-bool-golang/#respond Sun, 23 Feb 2020 08:19:00 +0000 https://vikasboss.github.io/?p=1454 strconv.ParseBool() function can be used to parse a string representation of a bool. https://golang.org/pkg/strconv/#ParseBool Below is the signature of the function Let’s see a working code Output:

The post Parse a bool or Check if given string is a bool in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
strconv.ParseBool() function can be used to parse a string representation of a bool.

https://golang.org/pkg/strconv/#ParseBool

Below is the signature of the function

func ParseBool(str string) (bool, error)

Let’s see a working code

package main

import (
    "fmt"
    "strconv"
)

func main() {
    input := "true"
    if val, err := strconv.ParseBool(input); err == nil {
        fmt.Printf("%T, %v\n", val, val)
    }

    input = "false"
    if val, err := strconv.ParseBool(input); err == nil {
        fmt.Printf("%T, %v\n", val, val)
    }

    input = "garbage"
    if val, err := strconv.ParseBool(input); err == nil {
        fmt.Printf("%T, %v\n", val, val)
    } else {
        fmt.Println("Given input is not a bool")
    }
}

Output:

bool, true
bool, false
Given input is not a bool

The post Parse a bool or Check if given string is a bool in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
https://vikasboss.github.io/check-string-bool-golang/feed/ 0 1454