Here, We will see how to convert int to string in go. We can do it by using Itoa() and FormatInt() function in strconv package in go golang.
Itoa() or FormatInt() are used to convert an int value to string in go.
There are many ways to convert integer into string in go.
- Itoa()
- FormatInt()
- Sprintf()
By using Itoa()
—–
Function prototype:
func Itoa(i int) string Input Parameter: Input parameter must be a 32 bit integer, otherwise you would get the compile error.
Return value:
Itoa() function in strconv package returns
string value of integer.
Example with code:
package main
import (
"fmt"
"strconv"
)
func main() {
i := 20
s := strconv.Itoa(i)
fmt.Printf("%T, %v\n", s, s)
}
Output:
string, 20
By using FormatInt()
—–
Function prototype:
func FormatInt(i int64, base int) string Input Parameter: Input parameter must be a 64 bit integer, otherwise you would get the compile error.
Return value:
FormatInt() function in strconv package returns
string representation of i in the given base,
for 2 <= base <= 36.
Example with code:
package main
import (
"fmt"
"strconv"
)
func main() {
v := int64(24)
b10 := strconv.FormatInt(v, 10)
fmt.Printf("%T, %v\n", b10, b10)
b16 := strconv.FormatInt(v, 16)
fmt.Printf("%T, %v\n", b16, b16)
b2 := strconv.FormatInt(v, 2)
fmt.Printf("%T, %v\n", b2, b2)
}
Output:
string, 24
string, 18
string, 11000
By using Sprintf()
—–
Function prototype:
func Sprintf(format string, a ...interface{}) string
Return value:
Sprintf() function in fmt package formats
according to a format specifier and returns
the resulting string.
Example with code:
package main
import (
"fmt"
)
func main() {
val := fmt.Sprintf("%v", 10)
fmt.Printf("%T, %v\n", val, val)
val = fmt.Sprintf("%v", -10)
fmt.Printf("%T, %v\n", val, val)
val = fmt.Sprintf("%v", 0x101010)
fmt.Printf("%T, %v\n", val, val)
}
Output:
string, 10
string, -10
string, 1052688
To learn more about golang, Please refer given below link:
https://techieindoor.com/go-lang-tutorial/
References:
https://golang.org/doc/
https://golang.org/pkg/