Golang有一个内置包叫strconv ,提供了将int转换为string的函数。我已经在这篇博客中介绍了如何将字符串转换为int。请随意查看。
Golang的int转字符串
要将 Golang 的int转换为字符串,可以使用strconv.FormatInt()或strconv.Itoa() 函数。**FormatInt()**函数返回i在给定基数下的字符串表示,为2 <= 基数 <= 36。对于数字值>=10,结果使用小写字母'a'到'z'。
strconv.Itoa() 是 FormatInt(int64(i), 10)的 缩写。
Golang int/int64到字符串
Go(Golang)直接从标准库strconv中的一个包中提供了字符串和整数转换。
在 Golang 中,要将一个整数值转换为字符串,我们可以使用 strconv 包中的 FormatInt 函数。
func FormatInt(i int64, base int) string
Golang的FormatInt()函数返回i在给定基数下的字符串表示,适用于2 <= base <= 36。最后的结果是使用小写字母'a'到'z'表示数字值>=10。
例子
// hello.go
package main
import (
"fmt"
"reflect"
"strconv"
)
func main() {
info := 1121
/** converting the info variable into a string using FormatInt method */
str2 := strconv.FormatInt(int64(info), 10)
fmt.Println(str2)
fmt.Println(reflect.TypeOf(str2))
}
输出
go run hello.go
1121
string
我们使用了reflect 包中的Typeof() 方法来确定数据类型,它是一个字符串。此外,Golang反映包有检查变量类型的方法。然后,我们使用**FormatInt()**方法将Golang的int转换为字符串。
func Itoa(i int) string
Golang strconv.Itoa()等同于FormatInt(int64(i), 10)。
让我们看看如何使用这些函数将一个整数转换为ASCII字符串的例子。
// hello.go
package main
import (
"fmt"
"reflect"
"strconv"
)
func main() {
info := 1121
fmt.Println(reflect.TypeOf(info))
/** converting the info variable into a string using FormatInt method */
str2 := strconv.Itoa(info)
fmt.Println(str2)
fmt.Println(reflect.TypeOf(str2))
}
输出
go run hello.go
int
1121
string
在普通转换中,该值被解释为Unicode码位,产生的字符串将包含由该码位编码的UTF-8代表的字符。
请看下面的代码。
package main
import (
"fmt"
"reflect"
)
func main() {
s := 97
fmt.Println(reflect.TypeOf(s))
/** converting the info variable into a string using FormatInt method */
str2 := string(97)
fmt.Println(str2)
fmt.Println(reflect.TypeOf(str2))
}
輸出
go run hello.go
int
a
string
结论
Golang strconv包提供了FormInt()和Itoa()函数来转换go整数到字符串,我们可以使用refect包来验证数据类型。