How to use the strconv.ParseBool() function in Golang

Golang strconv.ParseBool() function

The ParseBool() function returns the value in the boolean form represented by the string that is provided. It belongs to a strconv package. It only accepts 1, t, T, TRUE, true, True, 0, f, F, FALSE, false, and False. Values other than this will show an error.

Syntax

func ParseBool(str string) (bool, error)

Parameter

  • str: The value of string that gets parsed to the boolean value .

Return type

The returned value is a bool, error type.

Return value

The ParseBool() function returns the boolean value represented by the string.

Code

The following program shows how to implement the strconv.ParseBool() function in Golang:

// Golang program
// strconv.ParseBool() Function
package main
import (
"fmt"
"strconv"
)
func main() {
//function ParseBool() returns the boolean value
// represented by the string.
fmt.Println(strconv.ParseBool("1"))
fmt.Println(strconv.ParseBool("false"))
fmt.Println(strconv.ParseBool("TRUE"))
fmt.Println(strconv.ParseBool("1"))
fmt.Println(strconv.ParseBool("F"))
// This will throw an error
fmt.Println(strconv.ParseBool("trUe"))
}

Explanation

  • Line 1: We add the main package.

  • Lines 3 to 6: We import the necessary packages in Golang project.

  • Lines 11 to 21: We define the main() function and the strconv.ParseBool() function, which checks whether the string passed is a boolean value or not.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources