Golang有一个名为strconv 的内置包,提供了将int转换为字符串的函数。
Golang的int转字符串
在Golang中,要将一个int类型转换为字符串,可以使用以下方法之一。
- strconv.FormatInt。FormatInt返回i在给定基数下的字符串表示,为2 <= 基数 <= 36。对于数字值>=10,结果使用小写字母'a'到'z'。
- strconv.Itoa:Itoa是FormatInt(int64(i), 10)的简写。
我已经在这个博客中写过如何将字符串转换为int。
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包来验证数据类型。