How to save struct into file?

848 views
Skip to first unread message

dlin

unread,
Jun 17, 2011, 10:00:38 PM6/17/11
to golang-nuts
I'm trying to write a convert file format sample.
There some questions in this process stopped me.

1. How to convert struct into byte string?
2. How to save struct into file in a simple line (maybe by io/ioutil)?
3. Is there simpler Go syntax to declare initial array value?

func genSample(fName string) {
h := Header_v1_t{Version:1, BlockCnt:3}
b1s := []B1_v1_t{ B1_v1_t{1, 2, 3}, B1_v1_t{1, 4, 5}, B1_v1_t{1, 6,
7}}
b2s := []B2_v1_t{
B2_v1_t{2, 4, 5, [2]uint16{6,7}, [8]byte{8,9,10,11,12,13,14,15}},
B2_v1_t{2, 6, 7, [2]uint16{8,9}, [8]byte{9,10,11,12,13,14,15,16}},
B2_v1_t{2, 8, 9, [2]uint16{1,2}, [8]byte{10,11,12,13,14,15,16,17}}}
d := []byte(h) // FIXME: compile failed
fmt.Printf("%#v\n%#v\n%#v\n%#v", h, b1s, b2s, d)
}
type Header_v1_t struct {
Version uint16 //= 1
BlockCnt uint8
}
type B1_v1_t struct {
Tag uint8 // = 1
A uint16
B uint32
}
type B2_v1_t struct {
Tag uint8 // = 2
E uint16
F uint8
G [2]uint16
H [8]byte
}

Ostsol

unread,
Jun 17, 2011, 10:22:19 PM6/17/11
to golang-nuts
1, 2) Take a look at the following packages: encoding/binary, gob, and
json. You could even probably perform some casting magic via the
unsafe package, but that's not recommended as it's, well, unsafe.
3) How about something like:

b1s := []B1_v1_t{ {1, 2, 3}, {1, 4, 5}, {1, 6, 7}}

You may omit the struct name in such a slice-literal.

-Daniel

CrossWall

unread,
Jun 17, 2011, 10:55:37 PM6/17/11
to golan...@googlegroups.com
g := gob.NewEncoder(os.Stdout)
g.Encode(myStruct)
Reply all
Reply to author
Forward
0 new messages