Go语言int类型转换为string类型 - 详细指南
Go语言中,可以使用 strconv 包中的函数将 int 类型转换为 string 类型。
有两个主要的函数可用于此目的:
- strconv.Itoa():将 int 类型转换为对应的十进制字符串。
- strconv.FormatInt():将 int 类型转换为指定进制的字符串。
以下是使用这两个函数的示例代码:
package main
import (
"fmt"
"strconv"
)
func main() {
// 使用 strconv.Itoa() 将 int 转换为字符串
num := 42
str := strconv.Itoa(num)
fmt.Println(str) // 输出: '42'
// 使用 strconv.FormatInt() 将 int 转换为二进制字符串
num2 := 42
str2 := strconv.FormatInt(int64(num2), 2)
fmt.Println(str2) // 输出: '101010'
}
请注意,在使用strconv.FormatInt()函数时,需要将 int 类型的值转换为 int64 类型,以便与函数的参数类型匹配。
希望对你有所帮助!
原文地址: https://www.cveoy.top/t/topic/pePQ 著作权归作者所有。请勿转载和采集!