How to Convert Int to String in Golang

1. Introduction

Conversion between different types is a common requirement in programming languages. In Go, you may frequently need to convert integers to strings, especially when dealing with functions that require string parameters. This post will explore how to convert an integer to a string in Go using the strconv package.

Definition

In Go, the strconv package provides the Itoa (integer to ASCII) function for converting an int to a string. For other integer types or to format numbers in different bases, FormatInt or FormatUint can be used.

2. Program Steps

1. Import the strconv package.

2. Convert an int to a string using strconv.Itoa.

3. Convert an int64 to a string in a specific base using strconv.FormatInt.

3. Code Program

package main

import (
	"fmt"
	"strconv"
)

func main() {
	// Convert an int to a string using strconv.Itoa
	number := 42
	str := strconv.Itoa(number)
	fmt.Println("String value:", str)

	// Convert an int64 to a string with a specific base using strconv.FormatInt
	bigNumber := int64(1234567890)
	base10Str := strconv.FormatInt(bigNumber, 10)
	fmt.Println("Base 10 string value:", base10Str)
}

Output:

String value: 42
Base 10 string value: 1234567890

Explanation:

1. package main - The package declaration for the Go program.

2. import "fmt" and import "strconv" - Import the necessary packages for formatted output and string conversion functions.

3. number is an integer variable that holds the value 42.

4. strconv.Itoa is called to convert number to its string representation.

5. bigNumber is an int64 variable that holds a larger integer value.

6. strconv.FormatInt is called with bigNumber and the base 10 to convert the number to its string representation in base 10.

7. The fmt.Println function calls print the string representations of both integers.

8. The output shows the integers 42 and 1234567890 converted to their string equivalents.


Comments