How to convert String to Boolean Data Type Conversion in Go?
Like most modern languages, Golang includes strings as a built-in type. Let's take an example, you may have a string that contains a boolean value "true". However, because this value is represented as a string, you can't perform any operation on it. You need to explicitly convert this string type into an boolean type before you can perform any operation on it.
String to Boolean Conversion
Package strconv is imported to perform conversions to and from string.ParseBool returns the boolean value represented by the string. It accepts 1, t, T, TRUE, true, True, 0, f, F, FALSE, false, False. Any other value returns an error.
Example
package main
import (
"fmt"
"strconv"
)
func main() {
s1 := "true"
b1, _ := strconv.ParseBool(s1)
fmt.Printf("%T, %v\n", b1, b1)
s2 := "t"
b2, _ := strconv.ParseBool(s2)
fmt.Printf("%T, %v\n", b2, b2)
s3 := "0"
b3, _ := strconv.ParseBool(s3)
fmt.Printf("%T, %v\n", b3, b3)
s4 := "F"
b4, _ := strconv.ParseBool(s4)
fmt.Printf("%T, %v\n", b4, b4)
}
Output
bool, true
bool, true
bool, false
bool, false
Most Helpful This Week
Golang Program to print Triangle of Numbers
Golang panic recover example
How to add items to Slice using append function in Golang?
Modernizing Legacy Applications: Critical Tips for Organizational Upgrades
Defining a type that satisfies an interface in Go Programming Language
Golang Program to print numbers with diamond pattern
Golang program for implementation of Pancake Sort
Polymorphism in Go Programming Language
GO supports the standard arithmetic operators: (Addition, Subtraction, Multiplication, Division,Remainder)
How do you handle HTTP authentication with an HTTP client in Go?
Most Helpful This Week
Various examples of Carbon date-time package in GolangHow to extract text from between html tag using Regular Expressions in Golang?Constructors in GolangHow to use Ellipsis (...) in Golang?Example: How to use ReadAtLeast from IO Package in Golang?How to use for and foreach loop?Example: Split, Join, and Equal from BYTES PackageReplace numbers by zero from stringHow to read current directory using Readdir?Regular expression to extract text between square brackets