Go语言的string和byte slice之间的转换

栏目: Go · 发布时间: 6年前

内容简介:A string contains an array of bytes that, once created, is immutable. By contrast, the elements of a byte slice can be freely modified.Strings can be converted to byte slices and back again:Conceptually, the []byte(s) conversion allocates a new byte array

A string contains an array of bytes that, once created, is immutable. By contrast, the elements of a byte slice can be freely modified.

Strings can be converted to byte slices and back again:

s := “abc”

b := []byte(s)

s2 := string(b)

Conceptually, the []byte(s) conversion allocates a new byte array holding a copy of the bytes of s, and yields a slice that references the entirety of that array. An optimizing compiler may be able to avoid the allocation and copying in some cases, but in general copying is required to ensure that the bytes of s remain unchanged even if those of b are subsequently modified. The onversion from byte slice back to string with string(b) also makes a copy, to ensure immutability of the resulting string s2。

1 在Golang 中string 是不可改变的修改的。

2 []byte转string的时候需要分配一次内存

3 string 转[]byte的时候也需要分配一次内存


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

CSS设计指南

CSS设计指南

史密斯 / 李松峰 / 人民邮电出版社 / 2013-5 / 59.00元

《图灵程序设计丛书:CSS设计指南(第3版)》是一本面向初中级读者的经典设计指南。全书共分8章,前4章分别介绍了HTML标记和文档结构、CSS工作原理、定位元素、字体和文本,对规则、声明、层叠、特指度、选择符等基本概念进行了详细解读。随后4章介绍了页面布局、界面组件,CSS3圆角、阴影、渐变、多背景等视觉设计技巧,最后还对如何实现最前沿的响应式设计进行了通俗易懂的演示。一起来看看 《CSS设计指南》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

MD5 加密
MD5 加密

MD5 加密工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具