How to convert String to Boolean type in GoLang | GoLang Tutorial
5 years ago Lalit Bhagtani 0
In this tutorial, we will learn about how to convert string to boolean type in Go programming language.
ParseBool
The function ParseBool converts the string to a boolean value. It can accepts 1, t, T, TRUE, true, True for true boolean value and 0, f, F, FALSE, false, False for false boolean value. Any other value will return an error.
Syntax
func ParseBool(str string) (b bool, err error)
Example
package main
import (
"fmt"
"strconv"
)
func main() {
var (
Tfirst = "T"
Tsecond = "1"
Tthird = "True"
Ffirst = "F"
Fsecond = "0"
Fthird = "False"
Err = "TFalse"
)
first, _ := strconv.ParseBool(Tfirst)
fmt.Printf("%T, %v\n", first, first)
second, _ := strconv.ParseBool(Tsecond)
fmt.Printf("%T, %v\n", second, second)
third, _ := strconv.ParseBool(Tthird)
fmt.Printf("%T, %v\n", third, third)
fourth, _ := strconv.ParseBool(Ffirst)
fmt.Printf("%T, %v\n", fourth, fourth)
fifth, _ := strconv.ParseBool(Fsecond)
fmt.Printf("%T, %v\n", fifth, fifth)
sixth, _ := strconv.ParseBool(Fthird)
fmt.Printf("%T, %v\n", sixth, sixth)
seventh, error := strconv.ParseBool(Err)
fmt.Printf("%T, %v, %v\n", seventh, seventh, error)
}
Output
bool, true
bool, true
bool, true
bool, false
bool, false
bool, false
bool, false, strconv.ParseBool: parsing "TFalse": invalid syntax
References
That’s all for how to convert string to boolean type in Go programming language. if you liked it, please share your thoughts in comments section and share it with others too.