I have seen people use unsafe.Pointer
to efficiently convert a []byte
to a string
. https://play.golang.org/p/uz84H54VM8
var b = []byte{'f', 'o', 'o', 'b', 'a', 'r'}
var s = *(*string)(unsafe.Pointer(&b))
I understand what it is doing as well as the dangers involved in general but have a question about the memory.
Since the structure of a slice has a data pointer, a length, and a capacity, but the string doesn't have the capacity, what happens to that memory if b
was created on the heap? Does the garbage collector know that it needs to track the capacity separately? Or could this cause a memory leak?
EDIT:
I understand how to reslice strings and slices. The above code is for when you need to convert from []byte
to string
but want to avoid a full copy.
The question is about the capacity
that we're dropping from the structure and if it causes GC problems.