This question already has an answer here:
How to convert a slice of bytes to []uint16
and reverse without allocation new uint16
slice. This question focused on performance and memory consumption
</div>
This question already has an answer here:
How to convert a slice of bytes to []uint16
and reverse without allocation new uint16
slice. This question focused on performance and memory consumption
</div>
Consider that converting = copying, except for two special cases: m:=map[string]int{};m[string(bytes))
has no allocation, similarly with append.
Using unsafe.Pointer seems the current workaround (as its name suggests, "unsafe")
u16 := *(*uint16)(unsafe.Pointer(&byte_array[4]))
There is a proposal to use unsafe.Slice
instead.
There is also the (rejected for now) proposal golang/go issue 13656
The problem is having to write
(*[C]T)(unsafe.Pointer(v))[:n:n]
, for some C, T, v, and n.A simpler way to write that entire expression would be ideal.
var s []byte = C.AsSlice((*byte)(ptr), n)