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 ๐Ÿ‘

Premium Content

You can get all the below premium content directly in your mail when you subscribe us

Books

Portfolio Template

View | Get Source Code

Cheat Sheets

Cheat Sheets Books are basically Important useful notes which we use in our day-to-day life.

I'm working on some more Cheat Sheets book on Jquery, TypeScript, React js and for other languages. I will send it once it's completed.

Stay tuned working on React Js Cheat Sheets Book

Related Posts