how to convert string to bool in golang?
September 16, 2022Hi Friends 👋,
Welcome To aGuideHub! ❤️
To convert string to bool in golang, just use strconv.ParseBool()
method and assign your value it will convert string to bool. Only you have to pass string into an ParseBool()
method.
Follow the below tutorial if you are struggling with installing GO in windows.
https://aguidehub.com/blog/how-to-install-golang-in-windows/
Today, I will show you how do I convert string to bool in golang, as above mentioned I’m going to use ParseBool()
way.
The strconv
package provide ParseBool()
method.
The ParseBool()
method convert true
for "1"
, "t"
, "T"
, "TRUE"
, "true"
, "True"
. and false
for "0"
, "f"
, "F"
, "FALSE"
, "false"
, "False"
.
Let’s start our Golang convert string to bool example
Convert whole string into boolean example
main.go
package main
import (
"fmt"
"strconv"
)
func main() {
// truth cases example
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 := "1"
b3, _ := strconv.ParseBool(s3)
fmt.Printf("%T, %v\n", b3, b3)
// false cases example
s4 := "0"
b4, _ := strconv.ParseBool(s4)
fmt.Printf("%T, %v\n", b4, b4)
s5 := "F"
b5, _ := strconv.ParseBool(s5)
fmt.Printf("%T, %v\n", b5, b5)
s6 := "false"
b6, _ := strconv.ParseBool(s6)
fmt.Printf("%T, %v\n", b6, b6)
}
In the above example, we have converted string to boolean and printed in golang console. let’s check the output.
Output
bool, true
bool, true
bool, true
bool, false
bool, false
bool, false
I hope it helps you, All the best 👍.