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)
dongtui9168 好的,我认为当我将AAAA附加到BBBB中的次数正确时,它应该能够读取完整的字节字符串。感谢@JimB的帮助
接近 3 年之前 回复
dongyu5482 二进制包只能自动解码为固定大小的值。它不知道Bd字段是一个uint16(?),指示正在跟随多少AAAA。如果手动解码,您将不得不做一些事情。
接近 3 年之前 回复


https://golang.org/pkg/encoding/binary/#Read 说:</ p>

数据必须是指向固定值的指针 -size值或固定大小的值的一部分。</ p>
</ blockquote>

,这意味着必须在以下位置读取 Read </ code>的类型的大小 编译时间。 您的 struct BBBB </ code>包含一片 [] AAAA </ code>,这意味着它的长度仅在运行时已知。 如果将其设置为固定大小的数组,例如 [16] AAAA </ code>,它将起作用。</ p>
</ div>



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. Your struct 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.

Csdn user default icon