从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?
答案 0 :(得分:5)
两种情况都是。
String types是不可变的。因此,将它们转换为可变slice type将分配一个新切片。另请参阅http://blog.golang.org/go-slices-usage-and-internals
与逆相同。否则,改变切片会改变字符串,这会违反规范。