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.Atoi
value, err := strconv.ParseInt("123", 10, 64)int64
简写方式(只支持 10 进制):
立即学习“go语言免费学习笔记(深入)”;
num, err := strconv.Atoi("123") // 等价于 ParseInt("123", 10, 0)注意:Atoi 更方便,但功能有限,适合简单场景。
strconv.ParseUint
u, err := strconv.ParseUint("456", 10, 64)用于解析非负整数,比如
uint
uint32
uint64
strconv.ParseFloat
f, 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.FormatInt
s := strconv.Itoa(123) // 最常用,等价于 FormatInt(123, 10)
更通用的方式:
s := strconv.FormatInt(123, 10) // 支持不同进制
比如转成二进制:
bin := strconv.FormatInt(10, 2) // "1010"
strconv.FormatUint
s := strconv.FormatUint(456, 10)
strconv.FormatFloat
s := strconv.FormatFloat(3.1415, 'f', 2, 64)
参数说明:
'f'
3.14
'e'
3.14e+00
'g'
strconv.FormatBool
s := 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
以上就是Golang的strconv库怎么用 字符串与基本类型转换方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号