×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang strconv.ParseBool() Function with Examples

Golang | strconv.ParseBool() Function: Here, we are going to learn about the ParseBool() function of the strconv package with its usages, syntax, and examples.
Submitted by IncludeHelp, on September 07, 2021

strconv.ParseBool()

The ParseBool() function is an inbuilt function of the strconv package which is used to get the boolean value represented by the given string. The function accepts only 1, t, T, TRUE, true, True, 0, f, F, FALSE, false, False. Any other value returns an error.

It accepts a parameter (str string) and returns the boolean value represented by the str.

Syntax

func ParseBool(str string) (bool, error)

Parameters

  • str : String value which is to be parsed in the boolean.

Return Value

The return type of the ParseBool() function is (bool, error), it returns the boolean value represented by the string.

Example 1

// Golang program to demonstrate the
// example of strconv.ParseBool() Function

package main

import (
	"fmt"
	"strconv"
)

func main() {
	fmt.Println(strconv.ParseBool("true"))
	fmt.Println(strconv.ParseBool("True"))
	fmt.Println(strconv.ParseBool("TRUE"))
	fmt.Println(strconv.ParseBool("t"))
	fmt.Println(strconv.ParseBool("T"))
	fmt.Println(strconv.ParseBool("1"))
	fmt.Println()

	fmt.Println(strconv.ParseBool("false"))
	fmt.Println(strconv.ParseBool("False"))
	fmt.Println(strconv.ParseBool("FALSE"))
	fmt.Println(strconv.ParseBool("f"))
	fmt.Println(strconv.ParseBool("F"))
	fmt.Println(strconv.ParseBool("0"))
}

Output:

true <nil>
true <nil>
true <nil>
true <nil>
true <nil>
true <nil>

false <nil>
false <nil>
false <nil>
false <nil>
false <nil>
false <nil>

Example 2

// Golang program to demonstrate the
// example of strconv.ParseBool() Function

package main

import (
	"fmt"
	"strconv"
)

func main() {
	v := "true"

	s, err := strconv.ParseBool(v)
	if err == nil {
		fmt.Println("Parsing done...")
		fmt.Printf("%T, %v\n", s, s)
	} else {
		fmt.Println("Parsing failed...")
		fmt.Printf("Error:%v\n", err)
	}
	fmt.Println()

	v = "false"
	s, err = strconv.ParseBool(v)
	if err == nil {
		fmt.Println("Parsing done...")
		fmt.Printf("%T, %v\n", s, s)
	} else {
		fmt.Println("Parsing failed...")
		fmt.Printf("Error:%v\n", err)
	}
	fmt.Println()

	v = "No"
	s, err = strconv.ParseBool(v)
	if err == nil {
		fmt.Println("Parsing done...")
		fmt.Printf("%T, %v\n", s, s)
	} else {
		fmt.Println("Parsing failed...")
		fmt.Printf("Error:%v\n", err)
	}
	fmt.Println()
}

Output:

Parsing done...
bool, true

Parsing done...
bool, false

Parsing failed...
Error:strconv.ParseBool: parsing "No": invalid syntax

Golang strconv Package »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.