forked from agtorre/go-cookbook
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gob.go
48 lines (38 loc) · 773 Bytes
/
gob.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package encoding
import (
"bytes"
"encoding/gob"
"fmt"
)
// pos stores the x, y position
// for Object
type pos struct {
X int
Y int
Object string
}
// GobExample demonstrates using
// the gob package
func GobExample() error {
buffer := bytes.Buffer{}
p := pos{
X: 10,
Y: 15,
Object: "wrench",
}
// note that if p was an interface
// we'd have to call gob.Register first
e := gob.NewEncoder(&buffer)
if err := e.Encode(&p); err != nil {
return err
}
// note this is a binary format so it wont print well
fmt.Println("Gob Encoded valued length: ", len(buffer.Bytes()))
p2 := pos{}
d := gob.NewDecoder(&buffer)
if err := d.Decode(&p2); err != nil {
return err
}
fmt.Println("Gob Decode value: ", p2)
return nil
}