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
Normal function parameter with variadic function parameter
How to Remove duplicate values from Slice?
How to check if a string contains a numbers in Golang?
How to fetch an Integer variable as String in Go?
How to concatenate two or more slices in Golang?
The return values of a function can be named in Golang
How to write backslash in Golang string?
How To Make HTTP Requests in Go?
How to get the current date and time with timestamp in local and other timezones ?
Catch values from Goroutines