Technical things about conversion from []byte and string in Golang

huangapple go评论66阅读模式
英文:

Technical things about conversion from []byte and string in Golang

问题

string转换为[]byte会分配新的内存吗?同样,将[]byte转换为string会分配新的内存吗?

 s := "一个非常长的字符串"
 b := []byte(s) // 这会使内存需求翻倍吗?

 b := []byte{1,2,3,4,5, ...非常长的字节..}
 s := string(b) // 这会使内存需求翻倍吗?
英文:

Is it true that converting from string to []byte allocates new memory? Also, does converting from []byte to string allocates new memory?

 s := "a very long string"
 b := []byte(s) // does this doubled the memory requirement?

 b := []byte{1,2,3,4,5, ...very long bytes..}
 s := string(b) // does this doubled the memory requirement?

答案1

得分: 5

是的,在这两种情况下都是如此。

字符串类型 是不可变的。因此,将它们转换为可变的 切片类型 将会分配一个新的切片。参见 http://blog.golang.org/go-slices-usage-and-internals

反之亦然。否则,修改切片将会改变字符串,这将与规范相矛盾。

英文:

Yes in both cases.

String types are immutable. Therefore converting them to a mutable slice type will allocate a new slice. See also http://blog.golang.org/go-slices-usage-and-internals

The same with the inverse. Otherwise mutating the slice would change the string, which would contradict the spec.

huangapple
  • 本文由 发表于 2014年12月4日 19:40:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/27293131.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定