How to convert a string to int in Golang

  • 14 August 2020
  • ADM


How to convert a string to int in Golang - images/logos/golang.jpg


Here is a simple snippet how to convert a string into int in Golang. If you need help how to install Golang check the references links.


To convert a string to int you can use one of the following methods:

  • strconv.Atoi: Atoi returns the result of ParseInt(s, 10, 0) converted to type int.
  • strconv.ParseInt: ParseInt interprets a string s in the given base (2 to 36) and returns the corresponding value i.
package main

import (

func main() {

	str1 := "1234"

	/** converting the str1 variable into an int using Atoi method */
	i1, err := strconv.Atoi(str1)
	if err == nil {

	str2 := "5678"
	/** converting the str2 variable into an int using ParseInt method */
	i2, err := strconv.ParseInt(str2, 10, 64)
	if err == nil {


To compile the code navigate to the file location and run the following command.

$ go build string_to_int.go

Then depending if you are on Linux or Windows the binary file is created.

To run the application execute the command.


$ string_to_int


c:\Users\adm\go\tutorials> string_to_int.exe

If you want to compile and run the application in one single step run the following command:

go run string_to_int.go


Will display the i1/i2 variables types and the corresponding values.

Type: int
Type: int64