[英]Byte slice partial copy
I'm rather new with go and I'm trying to access a portion of a byte slice and copy to a another fixed length byte slice but doesn't find the proper solution.我对 go 相当陌生,我正在尝试访问字节片的一部分并复制到另一个固定长度的字节片,但找不到合适的解决方案。
My best bet was:我最好的选择是:
var extracted []byte
var newSlice [512]byte = extracted[0 : 511]
But this gives me a conversion error:但这给了我一个转换错误:
cannot use extracted[0:511] (value of type []byte) as [512]byte value in variable declarationcompilerIncompatibleAssign
Notes:笔记:
I thought I could use a io.Reader but this approach failed miserably as well.我以为我可以使用 io.Reader 但这种方法也失败了。
Any help welcome:)欢迎任何帮助:)
Here are a couple of approaches:这里有几种方法:
Convert the slice to an array pointer and dereference that pointer: 将切片转换为数组指针并取消引用该指针:
var pixels [512]byte pixels = *(*[512]byte)(extracted[:512])
This can be done in one statement using a short variable declaration :这可以使用简短的变量声明在一个语句中完成:
pixels:= *(*[512]byte)(extracted[:512])
Use the builtin copy function to copy elements from a slice to an array (this point was covered in the question comments):使用内置副本function 将元素从切片复制到数组(问题评论中涵盖了这一点):
var pixels [512]byte copy(pixels[:], extracted[:512])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.