how to use the package encoding/binary?

1,320 views
Skip to first unread message

R.wen Huang

unread,
Jul 12, 2011, 8:32:49 AM7/12/11
to golang-nuts
hi, 

I want to get data from stream(may be from serial port or networking),  and then put it to a struct type, can I use the binary package?

the following code seems not work, it throw a panic:
  "panic: binary.Read: invalid type main.oinfo"

could anyone tell  me what is wrong? thanks.

//////////////////////////////////////////////////////////////////////////
package main

import (
    "fmt"
    "os"
     "encoding/binary"    
)


type oinfo struct {
    a int 
    b byte
    c int
}


type pa [9]byte                

func (p pa) Read(b []byte) (n int, err os.Error) {

    for i:=byte(0); i<9; i++ {
        p[i] = i
    }
    
    fmt.Println(p)
        
    n = copy(b, p[:])
    
    return n, nil
    
}

func main() {
    
    fmt.Printf("hello world\n")
    
    var p pa
    var v oinfo
    err := binary.Read(p, binary.LittleEndian, &v)
    if err != nil {
        panic(err)
    }
    
    fmt.Println(v)
}

--
R.wen

Ostsol

unread,
Jul 12, 2011, 8:50:16 AM7/12/11
to golan...@googlegroups.com
At a glance, none of those struct fields are exported, so the package is unable to write to it.

-Daniel

yy

unread,
Jul 12, 2011, 8:56:56 AM7/12/11
to R.wen Huang, golang-nuts
2011/7/12 R.wen Huang <riwen...@gmail.com>:

> type oinfo struct {
>
> a int
>
> b byte
>
> c int
>
> }

From the pkg documentation: "Data must be a pointer to a fixed-size
value or a slice of fixed-size values. A fixed-size value is either a
fixed-size arithmetic type (int8, uint8, int16, float32, complex64,
...) or an array or struct containing only fixed-size values."

int is not a fixed size value, so oinfo is not a valid data argument.
The program should work if you define a and c as int32. However, you
will also need to export the fields or reflect will panic. If you use
this oinfo struct the program finishes correctly:

type oinfo struct {
A int32
B byte
C int32
}

It should probably be mentioned in the documentation that, if data is
a struct, its fields needs to pass the reflect.CanSet test or the
program will panic.

--
- yiyus || JGL .

R.wen Huang

unread,
Jul 12, 2011, 9:42:55 AM7/12/11
to yy, golang-nuts
thank you very much,  I was not much clear that 'int is not a fixed size value'. 

thanks.

--
R.wen
Reply all
Reply to author
Forward
0 new messages