strconv 是 Go 语言标准库中的一个包,用于在基本数据类型(例如整型、浮点型)和字符串之间进行转换。这个包提供了多个函数,用于将不同类型的数据转换为字符串,以及将字符串转换为不同类型的数据。下面是 strconv 包的一些常用函数和用法示例:
package main
import (
"fmt"
"strconv"
)
func main() {
// 整型转换为字符串
intNum := 42
strFromInt := strconv.Itoa(intNum)
fmt.Printf("整型转换为字符串:%s\n", strFromInt)
// 字符串转换为整型
str := "123"
intFromStr, err := strconv.Atoi(str)
if err != nil {
fmt.Println("转换错误:", err)
} else {
fmt.Printf("字符串转换为整型:%d\n", intFromStr)
}
// 浮点型转换为字符串
floatNum := 3.14
strFromFloat := strconv.FormatFloat(floatNum, 'f', -1, 64)
fmt.Printf("浮点型转换为字符串:%s\n", strFromFloat)
// 字符串转换为浮点型
strFloat := "3.14159"
floatFromStr, err := strconv.ParseFloat(strFloat, 64)
if err != nil {
fmt.Println("转换错误:", err)
} else {
fmt.Printf("字符串转换为浮点型:%f\n", floatFromStr)
}
// 布尔型转换为字符串
boolValue := true
strFromBool := strconv.FormatBool(boolValue)
fmt.Printf("布尔型转换为字符串:%s\n", strFromBool)
// 字符串转换为布尔型
strBool := "true"
boolFromStr, err := strconv.ParseBool(strBool)
if err != nil {
fmt.Println("转换错误:", err)
} else {
fmt.Printf("字符串转换为布尔型:%v\n", boolFromStr)
}
}
在上述示例中,我们展示了 strconv 包中的一些常用函数,这些函数用于将整型、浮点型、布尔型等数据转换为字符串,以及将字符串转换为相应的数据类型。需要注意的是,进行转换时要考虑到可能的错误情况,因此建议使用错误处理机制来处理异常情况。
此外,strconv 包还提供了其他函数,如处理进制转换、转义字符等。如果您需要了解更多函数和用法,可以查阅 Go 官方文档中的 strconv 包文档:https://pkg.go.dev/strconv