Different Ways to Convert an Integer Variable to String in Golang


In Go, converting an integer variable to a string can be accomplished in various ways. There are built-in functions and packages that can be used for this task. This article will explore different ways to convert an integer variable to a string in Go.

strconv.Itoa() Function

The strconv package provides a function called Itoa() which is used to convert an integer to its string representation. This function takes an integer value as an argument and returns its string representation.

Example

package main

import (
   "fmt"
   "strconv"
)

func main() {
   num := 123
   str := strconv.Itoa(num)
   fmt.Printf("Type: %T, Value: %s\n", str, str)
}

Output

Type: string, Value: 123

fmt.Sprintf() Function

The fmt package in Go provides a function called Sprintf() which is used to format strings. It is also used to convert an integer variable to a string. This function takes a format string and a list of values as arguments and returns the formatted string.

Example

package main

import (
   "fmt"
)

func main() {
   num := 123
   str := fmt.Sprintf("%d", num)
   fmt.Printf("Type: %T, Value: %s\n", str, str)
}

Output

Type: string, Value: 123

strconv.FormatInt() Function

The strconv package provides another function called FormatInt() which is used to convert an integer variable to a string. This function takes two arguments: the integer value and the base of the number system.

Example

package main

import (
   "fmt"
   "strconv"
)

func main() {
   num := int64(123)
   str := strconv.FormatInt(num, 10)
   fmt.Printf("Type: %T, Value: %s\n", str, str)
}

Output

Type: string, Value: 123

strconv.FormatUint() Function

Similar to the previous function, the strconv package provides another function called FormatUint() which is used to convert an unsigned integer variable to a string. This function also takes two arguments: the unsigned integer value and the base of the number system.

Example

package main

import (
   "fmt"
   "strconv"
)

func main() {
   num := uint64(123)
   str := strconv.FormatUint(num, 10)
   fmt.Printf("Type: %T, Value: %s\n", str, str)
}

Output

Type: string, Value: 123

Conclusion

Converting an integer variable to a string in Go can be accomplished using various built-in functions and packages. The most commonly used functions are strconv.Itoa() and fmt.Sprintf(). These functions provide an easy way to convert an integer variable to its string representation. The strconv package also provides FormatInt() and FormatUint() functions which are used to convert an integer and an unsigned integer to a string respectively.

Updated on: 12-Apr-2023

396 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements