4 ways to convert int to string in Go
Go: int to string conversion
Integer to string conversion is a type conversion or type casting, where an entity of integer data type is changed into string one.
In Golang, we can do the int to string conversion with the strconv.FormatInt
, strconv.Itoa
, or fmt.Sprintf
functions.
Go: int to string conversion using strconv.Itoa() function:
An integer can be converted to a string in Golang using the Itoa
function within the strconv
library. This library supports conversions to and from string representations to various other data types.
package main
import (
"fmt"
"strconv"
)
func main() {
i := 42
s := strconv.Itoa(i)
fmt.Printf("type of s: %T, s: %s\n", s, s)
}
Output:
type of s: string, s: 42
Go: int to string conversion using fmt.Sprintf() function:
fmt.Sprintf
function formats according to a format specifier and returns the resulting string.
package main
import (
"fmt"
)
func main() {
i := 42
s := fmt.Sprintf("%d", i)
fmt.Printf("type of s: %T, s: %s\n", s, s)
}
Output:
type of s: string, s: 42
Go: int to string conversion using strconv.FormatInt() function:
The strconv.FormatInt
returns the string representation of a value in the given base; where for 2 <= base <= 36
.
package main
import (
"fmt"
"strconv"
)
func main() {
i := int64(42)
s := strconv.FormatInt(i, 10)
fmt.Printf("type of s: %T, s: %s\n", s, s)
}
Output:
type of s: string, s: 42
Go: int to string conversion using string conversion (string()):
This approach is not recommended as it does not convert the integer to string correctly. It only converts the integer to a rune (a Unicode code point).
package main
import (
"fmt"
)
func main() {
i := 42
s := string(i)
fmt.Printf("type of s: %T, s: %s\n", s, s)
}
Output:
type of s: string, s: *
Previous Article
Golang Tutorials
- Hello World
- Operators in Go
- Declarations in Go
- Values in Go
- Variables in Go
- For in Go
- If/Else in Go
- Switch in Go
- Arrays in Go
- Slices in Go
- Maps in Go
- Range in Go
- Functions in Go
- Closures in Go
- Recursion in Go
- Pointers in Go
- Strings and Runes in Go
- Structs in Go
- Methods in Go
- Interfaces in Go
- Generics in Go
- Errors in Go
- Goroutines in Go
- Channels in Go
- Select in Go
- Timeouts in Go
- Timers in Go
- Worker Pools in Go
- WaitGroups in Go
- Mutexes in Go
- Sorting in Go
- Panic in Go
- Defer in Go
- Recover in Go
- JSON in Go
- XML in Go
- Time in Go
- Epoch in Go
- Time Formatting in Go
- Random Numbers in Go
- Number Parsing in Go
- URL Parsing in Go
- SHA256 Hashes in Go
- Base64 Encoding in Go
- Reading Files in Go
- Writing Files in Go
- File Paths in Go
- Directories in Go
- Testing and Benchmarking in Go
- Command-Line Arguments in Go
- Command-Line Flags in Go
- Command-Line Subcommands in Go
- Environment Variables in Go
- HTTP Client in Go
- HTTP Server in Go
- Context in Go
- Signals in Go