英文:
Copying a slice into a reflected array
问题
我有一个类似这样的结构:
type Record struct {
Name string
QuestionType [2]byte // 数组长度可以是任意的
Class [3]byte
}
我试图用来自bytes.Buffer
的字节填充这个结构(由于字节数据中的一些额外复杂性,我无法使用binary.Read
)。我使用reflect
包来迭代结构的元素,并从bytes.Buffer
中读取到结构中。
func fillStructure(buffer *bytes.Buffer) *Record {
// 现在是硬编码的,但以后将作为接口传入
myStruct := Record{}
reflectedStruct := reflect.ValueOf(&myStruct).Elem()
for i := 0; i < reflectedStruct.NumField(); i++ {
field := reflectedStruct.Field(i)
if field.Kind() == reflect.Array {
// 将字节从缓冲区复制到结构中
}
}
return &myStruct
}
然而,当我尝试用缓冲区的n个字节填充[n]byte数组时,我发现无法将buffer.Next(n)
返回的切片复制到结构体中的数组中。
field.Set()
不起作用,因为[]byte与[n]byte不兼容。copy()
不起作用,因为我找不到一种方法来获取结构体数组的切片。
问题: 有没有办法获取反射结构的数组的切片"视图",以便我可以将值复制进去?或者有其他方法将缓冲区返回的切片复制到结构体中?
英文:
I have a structure that looks like this:
type Record struct {
Name string
QuestionType [2]byte // Array may be arbitrary length
Class [3]byte
}
I am attempting to fill the structure with bytes from a bytes.Buffer
(I am unable to use binary.Read due to some additional complexity in the byte data.) I'm using the reflect
package to iterate over the elements of the structure, and read from the bytes.Buffer into the structure.
func fillStructure(buffer *bytes.Buffer) *Record {
// This is hard-coded now, but will be passed in as an interface later
myStruct := Record{}
reflectedStruct := reflect.ValueOf(&myStruct).Elem()
for i := 0; i < reflectedStruct.NumField(); i++ {
field := reflectedStruct.Field(i)
if field.Kind() == reflect.Array {
// Copy bytes from buffer into structure
}
}
return &myStruct
}
However, when I attempt to fill the [n]byte arrays with n bytes from the buffer, I find myself unable to copy the slice returned by buffer.Next(n)
into the array in the struct.
field.Set()
doesn't work because []byte is incompatible with [n]byte.copy()
doesn't work because I can't find a way to get a slice of the struct's array
Question: Is there a way to get a slice "view" of the reflected structure's array so I can copy the values in? Or some other way to copy the slice returned by buffer into the structure?
答案1
得分: 0
copy
函数可以在你“欺骗”数组以为它是一个切片的情况下工作。
copy(myStruct.QuestionType[:], buffer.Bytes())
在你的情况下,你可以使用reflect.Copy
结合上述技巧来实现:
if field.Kind() == reflect.Array {
srcArr := [2]byte{}
copy(srcArr[:], buffer.Bytes())
reflect.Copy(field, reflect.ValueOf(srcArr))
}
英文:
copy
does work if you "trick" the array into thinking it's a slice.
copy(myStruct.QuestionType[:], buffer.Bytes())
In your case, you can use reflect.Copy
together with the above technique like so:
if field.Kind() == reflect.Array {
srcArr := [2]byte{}
copy(srcArr[:], buffer.Bytes())
reflect.Copy(field, reflect.ValueOf(srcArr))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论