当前位置:网站首页>golang:[]byte转string
golang:[]byte转string
2022-07-02 18:09:00 【全栈程序员站长】
大家好,又见面了,我是你们的朋友全栈君。
golang中,字符切片[]byte转换成string最简单的方式是
package main
import (
"fmt"
_ "unsafe"
)
func main() {
bytes := []byte("I am byte array !")
str := string(bytes)
bytes[0] = 'i'//注意这一行,bytes在这里修改了数据,但是str打印出来的依然没变化,
fmt.Println(str)
}
打印信息:I am byte array !
上面的代码bytes在这里修改了数据,但是str打印出来的依然没变化,是因为[]byte的内存被拷贝了。接着看下面的代码
package main
import (
"fmt"
"unsafe"
)
func main() {
bytes := []byte("I am byte array !")
str := (*string)(unsafe.Pointer(&bytes))
bytes[0] = 'i'
fmt.Println(*str)
}
打印信息:i am byte array !
现在打印出来的信息已经是改变过的了,现在可以看出来str和bytes共用一片内存。
这样做的意义在于,在网络通信中,大多数的接受方式都是[]byte,如果[]byte的数据比较大,内存拷贝的话会影响系统的性能。
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/148601.html原文链接:https://javaforall.cn
边栏推荐
- 《病人家属,请来一下》读书笔记
- How to delete the border of links in IE? [repeat] - how to remove borders around links in IE? [duplicate]
- [100 cases of JVM tuning practice] 01 - introduction of JVM and program counter
- How to play when you travel to Bangkok for the first time? Please keep this money saving strategy
- Installation of thingsboard, an open source IOT platform
- Preprocessing and preprocessing macros
- How to enable the run dashboard function of idea
- R语言dplyr包filter函数筛选dataframe数据、如果需要筛选的数据列(变量)名称中包含引号则需要使用!!sym语法处理、否则因为无法处理引号筛选不到任何数据
- Crypto usage in nodejs
- Tutorial (5.0) 10 Troubleshooting * fortiedr * Fortinet network security expert NSE 5
猜你喜欢
How can retail enterprises open the second growth curve under the full link digital transformation
[paper reading] Ca net: leveraging contextual features for lung cancer prediction
Yunna | why use the fixed asset management system and how to enable it
聊聊电商系统中红包活动设计
Codeworks 5 questions per day (1700 average) - day 4
Web2.0的巨头纷纷布局VC,Tiger DAO VC或成抵达Web3捷径
Installation of thingsboard, an open source IOT platform
Markdown基础语法
【JVM调优实战100例】01——JVM的介绍与程序计数器
Develop fixed asset management system, what voice is used to develop fixed asset management system
随机推荐
Golang concurrent programming goroutine, channel, sync
Reduce -- traverse element calculation. The specific calculation formula needs to be passed in and combined with BigDecimal
Yunna | why use the fixed asset management system and how to enable it
高级性能测试系列《24. 通过jdbc执行sql脚本》
线程应用实例
Markdown基础语法
Progress-进度条
性能测试如何创造业务价值
Web2.0的巨头纷纷布局VC,Tiger DAO VC或成抵达Web3捷径
Page title component
日期工具类(不定时更新)
[0701] [paper reading] allowing data imbalance issue with perforated input during influence
Compile oglpg-9th-edition source code with clion
拦截器与过滤器的区别
How can retail enterprises open the second growth curve under the full link digital transformation
QT中的QPropertyAnimation使用和toast案列
Stratégie touristique d'été de Singapour: un jour pour visiter l'île de San taosha à Singapour
Why should we build an enterprise fixed asset management system and how can enterprises strengthen fixed asset management
新加坡暑假旅遊攻略:一天玩轉新加坡聖淘沙島
【测试开发】软件测试—概念篇