Welcome To Golang By Example

Menu
  • Home
  • Blog
  • Contact Us
  • Support this website
Menu

Parse a bool or Check if given string is a bool in Go (Golang)

Posted on February 23, 2020February 23, 2020 by admin

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
  • boolean
  • go
  • Follow @golangbyexample

    Popular Articles

    Golang Comprehensive Tutorial Series

    All Design Patterns in Go (Golang)

    Slice in golang

    Variables in Go (Golang) – Complete Guide

    OOP: Inheritance in GOLANG complete guide

    Using Context Package in GO (Golang) – Complete Guide

    All data types in Golang with examples

    Understanding time and date in Go (Golang) – Complete Guide

    ©2025 Welcome To Golang By Example | Design: Newspaperly WordPress Theme