golang的strconv库在字符串与数值转换时常见陷阱包括忽略错误返回、数值溢出或格式不匹配,最佳实践是:1. 永远检查错误,根据错误类型进行处理;2. 明确指定进制和位宽以避免隐式类型问题;3. 对简单情况使用atoi/itoa提高代码清晰度;4. 提前处理空字符串以避免解析失败;5. 提供默认值或回退逻辑确保程序健壮性。 strconv库还提供灵活的格式化选项,如formatint支持不同进制整数输出,formatfloat允许控制浮点数格式、精度及表示方式,适用于数据文件生成或日志记录等场景。此外,strconv库还包含实用但不为人知的功能,如append系列函数用于高效构建字符串,quote/unquote处理字符串字面量,parsebool/formatbool用于布尔值转换,这些功能在系统编程和工具开发中具有重要价值。

Golang的
strconv
strconv

strconv
字符串转数字:
立即学习“go语言免费学习笔记(深入)”;

strconv.Atoi(s string) (int, error)
int
ParseInt(s, 10, 0)
strconv.ParseInt(s string, base int, bitSize int) (int64, error)
base
bitSize
int
int8
int32
int64
strconv.ParseFloat(s string, bitSize int) (float64, error)
bitSize
float32
float64
数字转字符串:
strconv.Itoa(i int) string
Atoi
int
strconv.FormatInt(i int64, base int) string
int64
strconv.FormatFloat(f float64, fmt byte, prec int, bitSize int) string
fmt
prec
bitSize
这些函数都有一个共同点:它们会返回一个
error

package main
import (
"fmt"
"strconv"
)
func main() {
// 字符串转数字
sInt := "123"
ifInt, err := strconv.Atoi(sInt)
if err != nil {
fmt.Println("Atoi转换失败:", err)
} else {
fmt.Printf("字符串 \"%s\" 转为 int: %d\n", sInt, ifInt)
}
sFloat := "3.14159"
ifFloat, err := strconv.ParseFloat(sFloat, 64)
if err != nil {
fmt.Println("ParseFloat转换失败:", err)
} else {
fmt.Printf("字符串 \"%s\" 转为 float64: %f\n", sFloat, ifFloat)
}
// 数字转字符串
numInt := 456
sNumInt := strconv.Itoa(numInt)
fmt.Printf("int %d 转为字符串: \"%s\"\n", numInt, sNumInt)
numFloat := 2.71828
sNumFloat := strconv.FormatFloat(numFloat, 'f', 4, 64) // 保留4位小数
fmt.Printf("float64 %f 转为字符串 (保留4位小数): \"%s\"\n", numFloat, sNumFloat)
}在Go语言里,将字符串解析成数字,虽然
strconv
最常见的陷阱,我觉得就是忽略错误返回。很多初学者或者急于求成的人,会直接用
_
err
num, _ := strconv.Atoi("abc")num
另一个常见问题是数值溢出或格式不匹配。比如,你尝试把一个巨大的数字字符串解析成
int32
int32
ParseInt
ErrRange
"123a"
ParseInt
ParseFloat
ErrSyntax
最佳实践方面,我总结了几点:
if err != nil
strconv.ErrSyntax
strconv.ErrRange
ParseInt
base
ParseInt
ParseFloat
bitSize
int
0
bitSize
int
int32
int64
32
64
Atoi
Itoa
int
Atoi
Itoa
ParseInt(s, 10, 0)
FormatInt(int64(i), 10)
strconv.Atoi("")strings.TrimSpace
valStr := "abc"
val, err := strconv.Atoi(valStr)
if err != nil {
fmt.Printf("无法解析 \"%s\",使用默认值 0\n", valStr)
val = 0 // 默认值
}strconv
整数的格式化:strconv.FormatInt
FormatInt(i int64, base int)
int64
base
base = 10
base = 2
base = 8
base = 16
举个例子,一个数字
255
strconv.FormatInt(255, 10)
"255"
strconv.FormatInt(255, 2)
"11111111"
strconv.FormatInt(255, 16)
"ff"
我觉得这种灵活性非常好,它避免了我们自己去写复杂的进制转换逻辑,而且性能也经过了优化。
浮点数的格式化:strconv.FormatFloat
FormatFloat(f float64, fmt byte, prec int, bitSize int)
fmt
prec
fmt
'f'
3.14159
'e'
3.14159e+00
'e'
3.14159e+00
'g'
'f'
'e'
'g'
'g'
E
'x'
'x'
prec
'f'
'e'
'e'
prec
'g'
'g'
prec
prec
-1
-1
bitSize
float32
float64
例如:
value := 123.456789 fmt.Println(strconv.FormatFloat(value, 'f', 2, 64)) // "123.46" (四舍五入) fmt.Println(strconv.FormatFloat(value, 'e', 3, 64)) // "1.235e+02" fmt.Println(strconv.FormatFloat(value, 'g', 5, 64)) // "123.46" (总共5位有效数字) fmt.Println(strconv.FormatFloat(value, 'f', -1, 64)) // "123.456789" (完整精度)
这些选项让开发者可以非常灵活地控制数字的字符串表现形式,无论是为了用户界面显示、数据交换格式,还是内部日志记录,都能找到合适的方案。
除了我们最常用的
Atoi
Itoa
Parse
Format
strconv
Append
AppendBool(dst []byte, b bool) []byte
AppendInt(dst []byte, i int64, base int) []byte
AppendFloat(dst []byte, f float64, fmt byte, prec int, bitSize int) []byte
AppendQuote(dst []byte, s string) []byte
AppendQuoteRune(dst []byte, r rune) []byte
AppendQuoteToASCII(dst []byte, s string) []byte
这些函数不是直接返回
string
[]byte
strconv.AppendQuote
+
字符串字面量处理:Quote
Unquote
CanBackquote
Quote(s string) string
s
Unquote(s string) (string, error)
QuoteToASCII(s string) string
Quote
CanBackquote(s string) bool
这些函数在处理代码生成、解析配置文件或者需要严格遵循Go字符串规则的场景下非常强大。比如,如果你要动态生成一段Go代码,里面包含一个字符串变量,
Quote
布尔值转换:ParseBool
FormatBool
ParseBool(str string) (bool, error)
"1"
"t"
"t"
"TRUE"
"TRUE"
"TRUE"
true
"0"
"f"
"f"
"FALSE"
"FALSE"
"FALSE"
false
FormatBool(b bool) string
"TRUE"
"FALSE"
虽然看起来很简单,但在处理用户输入或配置项时,这些函数比手动判断字符串是否等于
"TRUE"
"FALSE"
ParseBool
这些“不那么显眼”的功能,其实是
strconv
以上就是Golang的strconv库如何进行类型转换 解析字符串与数值转换方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号