【转】go里面字符串转成 字节slice, 字节slice转成字符串
原文: https://yourbasic.org/golang/convert-string-to-byte-slice/#convert-string-to-bytes
---------------------------------------------------------------------------

Basics
When you convert between a string and a byte slice (array), you get a brand new slice that contains the same bytes as the string, and vice versa.
- The conversion doesn’t change the data;
- the only difference is that strings are immutable, while byte slices can be modified.
If you need to manipulate the characters (runes) of a string, you may want to convert the string to a rune slice instead. See Convert between rune array/slice and string.
Convert string to bytes
When you convert a string to a byte slice, you get a new slice that contains the same bytes as the string.
b := []byte("ABC€")
fmt.Println(b) // [65 66 67 226 130 172]
Note that the character €
is encoded in UTF-8 using 3 bytes. See the Go rune articlefor more on UTF-8 encoding of Unicode code points.
Convert bytes to string
When you convert a slice of bytes to a string, you get a new string that contains the same bytes as the slice.
s := string([]byte{65, 66, 67, 226, 130, 172})
fmt.Println(s) // ABC€
Performance
These conversions create a new slice or string, and therefore have time complexityproportional to the number of bytes that are processed.
More efficient alternative
In some cases, you might be able to use a string builder, which can concatenate strings without redundant copying:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
2018-07-31 linux 的计划任务 cron
2018-07-31 supervise 用来监控服务,自动启动
2018-07-31 tee -a /var/log/jd.log