GoLang - 填充结构数组 [英] GoLang - Populate Array of Structure
问题描述
我有以下2个结构
type AAAA struct {
Aa [2] byte
Ab [2]字节
Ac [3]字节
}
类型BBBB结构{
Ba [4]字节
Bb [2]字节
Bc [3]字节
Bd [2]字节//结构AAA项目的数目
BBStr [] AAAA
}
因此Struct BBB在Struct AAA中重复
然后我有一个字符串,它的输入包含结构作为输入
输入:=aaaabbccc02ddeefffddeefff(这里02是结构BBBB中Struct A AAAA重复的时间)
我需要读取输入字符串并填充结构BBBB,包括结构体数组AAA
我写了下面的函数来实现这个功能。但我得到了错误 - 二进制。阅读:无效类型* main.BBBB
需要帮助,以确定为什么会出现此错误?也有办法做到这一点不同?
$ b $ pre $ func main(){
input:=aaaabbccc02ddeefffddeefff
var k BBBB
变量j AAAA
k.BBStr =追加(k.BBStr,j)
k.BBStr =追加(k.BBStr,j)
xyz:= []字节(输入)
err:= binary.Read(bytes.NewReader(xyz),binary.LittleEndian,& k)
如果err!= nil {
fmt.Println(Bad error - ,err )
}
fmt.Println(Structure Definition - ,k)
}
https: //golang.org/pkg/encoding/binary/#Read 表示:
数据必须是指向固定 - 大小的价值或一块固定d
$ b这意味着您的
Read
类型的大小>必须在编译时知道。你的struct BBBB
包含一片[] AAAA
,这意味着它的长度只在运行时才被知道。如果你使它成为一个固定大小的数组,例如[16] AAAA
,它可以工作。I have the following 2 structures
type AAAA struct{ Aa [2]byte Ab [2]byte Ac [3]byte } type BBBB struct{ Ba [4]byte Bb [2]byte Bc [3]byte Bd [2]byte // No Of Struct AAA Items BBStr []AAAA }
So Struct BBB is repeating in Struct AAA
Then I have a string that I have as input which contains the value of the structure coming as input
input := "aaaabbccc02ddeefffddeefff" (here 02 is no of time Struct AAAA repeats in Struct BBBB)
I need to read through the input string and populate the structure BBBB including the array of structure AAA
I wrote the function below to achieve this. But I am getting " Bad error - binary.Read: invalid type *main.BBBB
Need Help in identifying why this error? Also is there a way to do this differently?
func main() { input := "aaaabbccc02ddeefffddeefff" var k BBBB var j AAAA k.BBStr = append(k.BBStr,j) k.BBStr = append(k.BBStr,j) xyz := []byte(input) err := binary.Read(bytes.NewReader(xyz), binary.LittleEndian, &k) if err != nil { fmt.Println("Bad error - ",err) } fmt.Println("Structure Definition - ",k) }
解决方案The documentation at https://golang.org/pkg/encoding/binary/#Read says:
Data must be a pointer to a fixed-size value or a slice of fixed-size values.
which means that the size of the type you
Read
must be known at compile time. Yourstruct BBBB
contains a slice of[]AAAA
which means its length is known only at run-time. If you make it a fixed-size array, e.g.[16]AAAA
, it would work.这篇关于GoLang - 填充结构数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!