Sep 162017

ADM

How to convert an int type to a string type in Golang

  • September 16 2017
  • ADM

 

 

How to convert an int type to a string type in Golang - golang

 

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

Code

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

  • strconv.FormatInt: FormatInt returns the string representation of i in the given base, for 2 <= base <= 36. The result uses the lower-case letters 'a' to 'z' for digit values >= 10.
  • strconv.Itoa: Itoa is shorthand for FormatInt(int64(i), 10)
package main

import (
	"fmt"
	"strconv"
)

func main() {

	i1 := 1234

	/** converting the i1 variable into a string using Itoa method */
	str1 := strconv.Itoa(i1)
	fmt.Println(str1)

	i2 := 5678
	/** converting the i2 variable into a string using FormatInt method */
	str2 := strconv.FormatInt(int64(i2), 10)
	fmt.Println(str2)
}

Compile&Run

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

$ go build int_to_string.go

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

To run the application execute the command.

Linux

$ int_to_string

Windows

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

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

go run int_to_string.go

Output

will display the int numbers in string format.

1234
5678

References