diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-16 19:23:18 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-16 19:23:18 +0000 |
commit | 43a123c1ae6613b3efeed291fa552ecd909d3acf (patch) | |
tree | fd92518b7024bc74031f78a1cf9e454b65e73665 /src/encoding/gob/example_encdec_test.go | |
parent | Initial commit. (diff) | |
download | golang-1.20-upstream.tar.xz golang-1.20-upstream.zip |
Adding upstream version 1.20.14.upstream/1.20.14upstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'src/encoding/gob/example_encdec_test.go')
-rw-r--r-- | src/encoding/gob/example_encdec_test.go | 61 |
1 files changed, 61 insertions, 0 deletions
diff --git a/src/encoding/gob/example_encdec_test.go b/src/encoding/gob/example_encdec_test.go new file mode 100644 index 0000000..e45ad4c --- /dev/null +++ b/src/encoding/gob/example_encdec_test.go @@ -0,0 +1,61 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package gob_test + +import ( + "bytes" + "encoding/gob" + "fmt" + "log" +) + +// The Vector type has unexported fields, which the package cannot access. +// We therefore write a BinaryMarshal/BinaryUnmarshal method pair to allow us +// to send and receive the type with the gob package. These interfaces are +// defined in the "encoding" package. +// We could equivalently use the locally defined GobEncode/GobDecoder +// interfaces. +type Vector struct { + x, y, z int +} + +func (v Vector) MarshalBinary() ([]byte, error) { + // A simple encoding: plain text. + var b bytes.Buffer + fmt.Fprintln(&b, v.x, v.y, v.z) + return b.Bytes(), nil +} + +// UnmarshalBinary modifies the receiver so it must take a pointer receiver. +func (v *Vector) UnmarshalBinary(data []byte) error { + // A simple encoding: plain text. + b := bytes.NewBuffer(data) + _, err := fmt.Fscanln(b, &v.x, &v.y, &v.z) + return err +} + +// This example transmits a value that implements the custom encoding and decoding methods. +func Example_encodeDecode() { + var network bytes.Buffer // Stand-in for the network. + + // Create an encoder and send a value. + enc := gob.NewEncoder(&network) + err := enc.Encode(Vector{3, 4, 5}) + if err != nil { + log.Fatal("encode:", err) + } + + // Create a decoder and receive a value. + dec := gob.NewDecoder(&network) + var v Vector + err = dec.Decode(&v) + if err != nil { + log.Fatal("decode:", err) + } + fmt.Println(v) + + // Output: + // {3 4 5} +} |