您的位置:首页 >Golang strconv库用法:字符串与类型转换教程
发布于2025-10-01 阅读(0)
扫一扫,手机访问
Go语言中strconv库用于字符串与基本类型的安全转换,1. 字符串转整数用ParseInt或简写的Atoi,后者仅支持10进制;2. 无符号整数用ParseUint;3. 浮点数用ParseFloat并指定精度;4. 布尔值用ParseBool,仅支持特定字符串;5. 整数转字符串推荐Itoa或FormatInt,支持多进制;6. 无符号整数用FormatUint;7. 浮点数用FormatFloat可控制格式和精度;8. 布尔值用FormatBool;实际使用时应优先选用Atoi和Itoa,注意检查Parse系列函数的错误返回,避免使用fmt.Sprintf进行类型转换以提升性能,该库命名规则统一,Parse用于转类型,Format用于转字符串,使用便捷。

Go 语言中的 strconv 库是处理字符串与基本数据类型之间转换的核心工具。它提供了安全、高效的方法,用于在字符串和整数、浮点数、布尔值等类型之间相互转换。下面介绍常用的方法及其使用方式。
当需要将字符串解析为数字或布尔值时,使用 ParseX 系列函数。
strconv.ParseInt 和 strconv.Atoivalue, err := strconv.ParseInt("123", 10, 64)int64 类型和错误。简写方式(只支持 10 进制):
num, err := strconv.Atoi("123") // 等价于 ParseInt("123", 10, 0)注意:
Atoi更方便,但功能有限,适合简单场景。
strconv.ParseUintu, err := strconv.ParseUint("456", 10, 64)用于解析非负整数,比如 uint、uint32、uint64。
strconv.ParseFloatf, err := strconv.ParseFloat("3.14", 64)第二个参数指定精度(32 或 64),返回 float64 或 float32 类型(需手动转换)。
strconv.ParseBool支持的字符串只有几个:
"true"、"false""True"、"False""1"、"0""t"、"f"b, err := strconv.ParseBool("true")如果字符串不是上述之一,会返回错误。
使用 FormatX 系列函数或更方便的 strconv.Itoa。
strconv.Itoa 和 strconv.FormatInts := strconv.Itoa(123) // 最常用,等价于 FormatInt(123, 10)
更通用的方式:
s := strconv.FormatInt(123, 10) // 支持不同进制
比如转成二进制:
bin := strconv.FormatInt(10, 2) // "1010"
strconv.FormatUints := strconv.FormatUint(456, 10)
strconv.FormatFloats := strconv.FormatFloat(3.1415, 'f', 2, 64)
参数说明:
'f':定点表示(如 3.14)'e':科学计数法(如 3.14e+00)'g':自动选择较短格式strconv.FormatBools := strconv.FormatBool(true) // "true"
优先使用 Atoi 和 Itoa:在整数转换中简单直观。
注意错误处理:所有 ParseX 函数都返回 (value, error),必须检查 err 是否为 nil。
num, err := strconv.Atoi("not-a-number")
if err != nil {
log.Fatal("转换失败:", err)
}避免用 fmt.Sprintf 做类型转换:虽然 fmt.Sprintf("%d", 123) 能转字符串,但性能不如 strconv,尤其在高频场景下。
进制转换很方便:比如 IP 地址处理、位运算调试时,用 FormatInt(x, 2) 看二进制很实用。
基本上就这些。strconv 的设计简洁明了,只要记住 Parse 是字符串转类型,Format 是类型转字符串,命名规则统一,用起来很顺手。
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
9