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.

Code

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 (
	"fmt"
	"strconv"
)

func main() {

	str1 := "1234"

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

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

Compile&Run

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.

Linux

$ string_to_int

Windows

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

Output

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

Type: int
1234
Type: int64
5678

 

References