简体   繁体   English

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

[英]Fast way of converting a slice of type T, to a slice of byte in Go

I have slices of different types, and I need to send them with TCP. 我有不同类型的切片,我需要使用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? 有什么方法可以将切片转换为[] byte,而无需遍历单个元素? For example, I want something like this (assuming mySlice elements are 4 Bytes here): 例如,我想要这样的东西(假设mySlice元素在这里是4个字节):

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

but it won't work, since 4 * len(mySlice) is not a constant. 但它不起作用,因为4 * len(mySlice)不是常数。

Thank you. 谢谢。

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. 我测试了不同的数组大小,它比仅当数组足够大时循环遍历单个元素(仅使用unsafe.Pointer)要好。

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. 要创建特定长度的切片,请使用make ,该长度不需要为常数。 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. 创建数组时,长度必须为常数,因为要创建的未命名类型必须在编译时可解析。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM