GoLang-填充结构数组

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

1个回答



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
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问