Golang字符串转换大全
在Golang中如何高效地进行各种字符串类型之间的转换?比如string与[]byte、int、float等基本类型互转,以及不同编码格式(如UTF-8和GBK)的转换?有哪些常用的标准库函数或第三方库推荐?转换过程中需要注意哪些性能问题和常见错误?
2 回复
Golang字符串转换常用方法:
- 字符串转数字:strconv.Atoi()
- 数字转字符串:strconv.Itoa()
- 字符串转字节:[]byte(str)
- 字节转字符串:string(bytes)
- 其他类型转换:strconv.FormatBool/ParseBool等 注意处理转换错误,使用strings包处理字符串操作。
更多关于Golang字符串转换大全的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
在Go语言中,字符串转换是常见操作,以下是一些常用场景及代码示例:
1. 字符串 ↔ 整数
- 字符串转整数:
s := "123" num, err := strconv.Atoi(s) // 返回 int // 或指定进制: num64, err := strconv.ParseInt(s, 10, 64) // 基础10,64位 - 整数转字符串:
num := 123 s := strconv.Itoa(num) // 或指定格式: s = strconv.FormatInt(int64(num), 10)
2. 字符串 ↔ 浮点数
- 字符串转浮点数:
s := "3.14" f, err := strconv.ParseFloat(s, 64) // 64位精度 - 浮点数转字符串:
f := 3.14 s := strconv.FormatFloat(f, 'f', 2, 64) // 格式 'f',保留2位小数
3. 字符串 ↔ 布尔值
- 字符串转布尔值:
s := "true" b, err := strconv.ParseBool(s) // 接受 "true", "1", "false", "0" - 布尔值转字符串:
b := true s := strconv.FormatBool(b) // 返回 "true" 或 "false"
4. 字符串 ↔ 字节数组([]byte)
- 字符串转字节数组:
s := "hello" bytes := []byte(s) - 字节数组转字符串:
bytes := []byte{104, 101, 108, 108, 111} s := string(bytes)
5. 字符串 ↔ 符文数组([]rune)
- 处理Unicode字符:
s := "你好" runes := []rune(s) // 转符文数组 s2 := string(runes) // 转回字符串
6. 大小写转换
- 使用
strings包:s := "Hello" lower := strings.ToLower(s) // "hello" upper := strings.ToUpper(s) // "HELLO"
7. 类型断言(接口转字符串)
- 当接口存储字符串时:
var i interface{} = "text" s, ok := i.(string) // 类型断言
8. 使用 fmt.Sprintf 格式化
- 通用转换:
num := 42 s := fmt.Sprintf("%d", num) // 转字符串
注意事项:
- 使用
strconv包进行基本类型转换时注意处理错误(如err != nil)。 - 字符串不可变,转换时可能产生新副本。
- 涉及中文或特殊字符时,优先用
rune处理。
以上方法覆盖了大部分字符串转换需求,根据具体场景选择合适函数。

