关于在Golang中从[]字节和字符串转换的技术问题

时间:2014-12-04 11:40:37

标签: memory-management go type-conversion

string转换为[]byte分配新内存是真的吗?此外,从[]byte转换为string是否会分配新内存?

 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 个答案:

答案 0 :(得分:5)

两种情况都是。

String types是不可变的。因此,将它们转换为可变slice type将分配一个新切片。另请参阅http://blog.golang.org/go-slices-usage-and-internals

与逆相同。否则,改变切片会改变字符串,这会违反规范。