在Go中将类型T的片转换为字节的片的快速方法

I have slices of different types, and I need to send them with TCP. The length of my slices is large, and not a constant value. Is there any way that I can convert the slices into []byte without looping through individual elements? For example, I want something like this (assuming mySlice elements are 4 Bytes here):

byteSlice := (*[4 * len(mySlice)]byte)(unsafe.Pointer(&mySlice[0]))

but it won't work, since 4 * len(mySlice) is not a constant.

Thank you.

In your sample code you're creating arrays, not slices, hence the error. To create a slice of a specific length, use make, which does not require the length to be a constant. When you create an array, the length must be a constant, because you're creating an unnamed type which must be resolvable at compile time.

So this is what I ended up doing (posting it as an answer to my question):

import "unsafe"
import "reflect"   

mySliceR := *(*reflect.SliceHeader)(unsafe.Pointer(&mySlice))
mySliceR.Len *= mySliceElemSize
mySliceR.Cap *= mySliceElemSize

byteSlice := *(*[]byte)(unsafe.Pointer(&mySliceR))

I tested it for different array sizes, and it is better than looping through individual elements (using only unsafe.Pointer) only when arrays are large enough.