How can I convert a string variable into Boolean, Integer or Float type in Golang?
The following source code snippet shows an abbreviated program with several String variables value parsed in Float, Boolean and Integer.
The parse functions
ParseBool
, ParseFloat
and ParseInt
convert strings to values. Hence String variable values getting stored as Boolean, Float and Integer in respective data types.
Example
package main
import (
"fmt"
"reflect"
"strconv"
)
func main() {
fmt.Println("\nConvert String into Boolean Data type\n")
str1 := "japan"
fmt.Println("Before :", reflect.TypeOf(str1))
bolStr,_ := strconv.ParseBool(str1)
fmt.Println("After :", reflect.TypeOf(bolStr))
fmt.Println("\nConvert String into Float64 Data type\n")
str2 := "japan"
fmt.Println("Before :", reflect.TypeOf(str2))
fltStr,_ := strconv.ParseFloat(str2,64)
fmt.Println("After :", reflect.TypeOf(fltStr))
fmt.Println("\nConvert String into Integer Data type\n")
str3 := "japan"
fmt.Println("Before :", reflect.TypeOf(str3))
intStr,_ := strconv.ParseInt(str3,10,64)
fmt.Println("After :", reflect.TypeOf(intStr))
}
Most Helpful This Week
How to collect information about garbage collection?
Convert specific UTC date time to PST, HST, MST and SGT
How to Convert string to integer type in Go?
Higher Order Functions in Golang
How to remove symbols from a string in Golang?
How to use a mutex to define critical sections of code and fix race conditions?
Regular expression to extract text between square brackets
How to use wildcard or a variable in our URL for complex routing?
Find element in a slice and move it to first position?
Regular expression for matching HH:MM time format in Golang