How to convert string to int in Golang?

Hi Friends ๐Ÿ‘‹,

Welcome To aGuideHub! โค๏ธ

To convert a string to int in Golang, use the strconv.Atoi() method it will convert your string to an integer you have to pass your string in the strconv.Atoi() method as a parameter only.

Converting datatype variables is a common task we will use every day in our coding life, so letโ€™s see how we can convert string to integer in Golang.

Follow the below tutorial if you are struggling in installing GO in windows.

https://aguidehub.com/blog/how-to-install-golang-in-windows

Here, we will use strconv package to convert string to int and reflect for know the data type of veriable.

To check data type example := https://aguidehub.com/blog/how-to-check-data-type-in-golang

package main

import (
    "fmt"
    "os"
    "strconv"
    "reflect"
)

func main() {
    s := "123";
    // string to int
    i, err := strconv.Atoi(s)
    if err != nil {
        // handle error
        fmt.Println(err)
        os.Exit(2)
    }
    fmt.Print(reflect.TypeOf(s).Kind(), reflect.TypeOf(i).Kind())
}

Output

Output:

string int

Try it yourself

All the best ๐Ÿ‘

Follow me on Twitter