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
Create and Print Multi Dimensional Slice in Golang
GO Program to Check Whether a Number is Palindrome or Not
Golang read file line by line to string
Golang program for implementation LIFO Stack and FIFO Queue
Go program to find MX records record of a domain
How do you send an HTTP POST request with an HTTP client in Go?
How do you write multi-line strings in Go?
GO Program to Generate Multiplication Table
Golang read json file into struct
How do you send an HTTP PATCH request in Go?
Most Helpful This Week
Regular expression to extract all Non-Alphanumeric Characters from a StringCreating a Function in GolangGolang Get current Date and Time in EST, UTC and MST?Example: Arrays of Arrays, Arrays of Slices, Slices of Arrays and Slices of SlicesEncoding and Decoding using json.Marshal and json.UnmarshalDifferent ways for Integer to String ConversionsHow to use Ellipsis (...) in Golang?Sample program to create csv and write dataAdd N number of Year, Month, Day, Hour, Minute, Second, Millisecond, Microsecond and Nanosecond to current date-timeHow to concatenate two or more slices in Golang?