...
Source file
src/encoding/gob/example_encdec_test.go
1
2
3
4
5 package gob_test
6
7 import (
8 "bytes"
9 "encoding/gob"
10 "fmt"
11 "log"
12 )
13
14
15
16
17
18
19
20 type Vector struct {
21 x, y, z int
22 }
23
24 func (v Vector) MarshalBinary() ([]byte, error) {
25
26 var b bytes.Buffer
27 fmt.Fprintln(&b, v.x, v.y, v.z)
28 return b.Bytes(), nil
29 }
30
31
32 func (v *Vector) UnmarshalBinary(data []byte) error {
33
34 b := bytes.NewBuffer(data)
35 _, err := fmt.Fscanln(b, &v.x, &v.y, &v.z)
36 return err
37 }
38
39
40 func Example_encodeDecode() {
41 var network bytes.Buffer
42
43
44 enc := gob.NewEncoder(&network)
45 err := enc.Encode(Vector{3, 4, 5})
46 if err != nil {
47 log.Fatal("encode:", err)
48 }
49
50
51 dec := gob.NewDecoder(&network)
52 var v Vector
53 err = dec.Decode(&v)
54 if err != nil {
55 log.Fatal("decode:", err)
56 }
57 fmt.Println(v)
58
59
60
61 }
62
View as plain text