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
Various examples of Carbon date-time package in Golang
How to write backslash in Golang string?
Regular Expression to get a string between parentheses in Golang
Create and Print Multi Dimensional Slice in Golang
How to find out element position in slice?
Example of Sscan vs Sscanf vs Sscanln from FMT Package