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
How to check if a string contains a white space in Golang?How to use a mutex to define critical sections of code and fix race conditions?Find element in a slice and move it to first position?Select single argument from all arguments of variadic functionReplace any non-alphanumeric character sequences with a dash using RegexRegular expression to validate email addressConvert Int data type to Int16 Int32 Int64Strip all white spaces, tabs, newlines from a stringHow to use for and foreach loop?Golang Get current Date and Time in EST, UTC and MST?