Golang如何使用strconv进行类型转换_Golang strconv类型转换方法实践

strconv包用于Go语言中字符串与基本类型间的转换,常用Atoi和Itoa实现整数与字符串互转,Parse和Format系列支持多进制、浮点及布尔类型转换,需始终检查错误以确保安全。

在Go语言中,strconv 包是处理基本数据类型与字符串之间转换的核心工具。无论是将数字转为字符串,还是解析字符串中的数值,都可以通过 strconv 高效完成。下面介绍常用的方法及其使用场景。

字符串与整数之间的转换

最常见的是 intstring 的互转,主要使用 strconv.Atoistrconv.Itoa

• 将字符串转为整数(Atoi):

使用 strconv.Atoi(s string) 可以将十进制字符串转为 int 类型。该函数返回两个值:结果和错误。如果字符串格式不合法,会返回错误。

示例:

s := "123"
n, err := strconv.Atoi(s)
if err != nil {
    log.Fatal("转换失败:", err)
}
// n = 123
• 将整数转为字符串(Itoa):

使用 strconv.Itoa(i int) 可将 int 转为对应的十进制字符串。

示例:

n := 456
s := strconv.Itoa(n)
// s = "456"

更灵活的数值解析与格式化

当需要处理不同进制、精度或非 int 类型时,可以使用更底层的 ParseFormat 系列函数。

• Parse 系列(字符串 → 数值):

用于 float、int、uint 等类型,支持指定位宽和进制。

  • strconv.ParseFloat(s, bitSize):解析浮点数,bitSize 为 32 或 64
  • strconv.ParseInt(s, base, bitSize):解析带进制的整数,base 可为 0(自动识别)、2、8、10、16
  • strconv.ParseUint(s, base, bitSize):同上,但结果为无符号整数

示例:解析十六进制数

s := "1a"
n, _ := strconv.ParseInt(s, 16, 64)
// n = 26
• Format 系列(数值 → 字符串):

将数值按指定格式转为字符串。

  • strconv.FormatFloat(f, 'g', -1, 64):将 float64 转为字符串
  • strconv.FormatInt(i, base):将 int64 按指定进制转为字符串
  • strconv.FormatUint(u, base):类似,用于 uint64

示例:将数字转为二进制字符串

n := int64(10)
s := strconv.FormatInt(n, 2)
// s = "1010"

布尔值的转换

strconv 也支持布尔类型的转换:

  • strconv.ParseBool:识别 "true"、"false"、"1"、"0" 等字符串
  • strconv.FormatBool:将 bool 转为 "true" 或 "false"

示例:

b, _ := strconv.ParseBool("1")
// b = true
s := strconv.FormatBool(true)
// s = "true"

基本上就这些。合理使用 strconv 能让字符串与基本类型之间的转换安全又高效。注意每次解析都应检查 error,避免程序因非法输入崩溃。