In Go, converting int values to string can be achieved in multiple ways. The most common approach is to use the Itoa function (an abbreviation for converting integers to ASCII strings) and the FormatInt function within the strconv package of the standard library. Here are some examples illustrating how to perform this conversion:
Using strconv.Itoa:
The strconv.Itoa function accepts an int type parameter and converts it to a string type.
gopackage main import ( "fmt" "strconv" ) func main() { intValue := 123 stringValue := strconv.Itoa(intValue) fmt.Println(stringValue) // Output: "123" }
Using strconv.FormatInt:
The strconv.FormatInt function is more flexible; it accepts an int64 type value and allows you to specify the base of the number. If you need to convert int to a decimal string, you can use it as follows:
gopackage main import ( "fmt" "strconv" ) func main() { intValue := 123 stringValue := strconv.FormatInt(int64(intValue), 10) // The second parameter 10 indicates decimal fmt.Println(stringValue) // Output: "123" }
Note that strconv.FormatInt requires an int64 type value. If your integer is of int type, you need to convert it to int64 first.
Using fmt.Sprintf:
The fmt.Sprintf function can be used for formatting strings, including converting int to string. This method is applicable to various formatting operations, not limited to integer conversion.
gopackage main import ( "fmt" ) func main() { intValue := 123 stringValue := fmt.Sprintf("%d", intValue) fmt.Println(stringValue) // Output: "123" }
In this example, %d is a format specifier indicating that an integer should be formatted as a decimal string.
These are common methods in Go for converting integers to strings. You can choose the appropriate method based on your specific needs.