Convert String to int, float, uint or boolean in Go

In real world application we come across the situation where one has to convert the data type from one to another.

GoLang is statically typed language and it supports different datatypes. In real world application we come across the situation where one has to convert the data type from one to another. Here in this example we will be covering different ways to convert string to other data type like int,  float, uint or boolean.
package main

import (
"fmt"
"strconv"
)

func main() {
fmt.Println("Convert string to int")
str_int := "10"
val_int, _ := strconv.ParseInt(str_int, 10, 64)
fmt.Printf("%d\n", val_int)

fmt.Println("Convert string to int using atoi")
val_atoi, _ := strconv.Atoi(str_int)
fmt.Printf("%d\n", val_atoi)

fmt.Println("Convert string to boolean")
str_bool := "true"
val_bool, _ := strconv.ParseBool(str_bool)
fmt.Printf("%b\n", val_bool)

fmt.Println("Convert string to float")
str_float := "123.23"
val_float, _ := strconv.ParseFloat(str_float, 64)
fmt.Printf("%f\n", val_float)

fmt.Println("Convert string to unsigned int")
str_uint := "1234"
val_uint, _ := strconv.ParseUint(str_uint, 10, 64)
fmt.Printf("%d\n", val_uint)
}

Output
Convert string to int
10
Convert string to int using atoi
10
Convert string to boolean
%!b(bool=true)
Convert string to float
123.230000
Convert string to unsigned int
1234

Never miss a post from Aditya Agrawal, when you sign up for Ednsquare.