GoLang - Populate Array of Structure

2019-09-19 09:21发布

问题:

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)
    }

回答1:

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.



标签: go struct