From 6c6b293d2705e65479f8e4781425cbd803b5cf24 Mon Sep 17 00:00:00 2001 From: Pavel Tisnovsky Date: Fri, 3 Jul 2020 18:45:07 +0200 Subject: [PATCH] Example #21: serializing basic data types into gob format --- .../marshalling/21_gob_marshal_basic_types.go | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 lesson7/marshalling/21_gob_marshal_basic_types.go diff --git a/lesson7/marshalling/21_gob_marshal_basic_types.go b/lesson7/marshalling/21_gob_marshal_basic_types.go new file mode 100644 index 0000000..19c6997 --- /dev/null +++ b/lesson7/marshalling/21_gob_marshal_basic_types.go @@ -0,0 +1,37 @@ +package main + +import ( + "bytes" + "encoding/gob" + "encoding/hex" + "fmt" +) + +func encodeAndDecode(msg string, value interface{}) { + var buffer bytes.Buffer + encoder := gob.NewEncoder(&buffer) + + err := encoder.Encode(value) + if err != nil { + fmt.Println(err) + } else { + content := buffer.Bytes() + fmt.Printf("%s value encoded into %d bytes\n", msg, len(content)) + encoded := hex.EncodeToString(content) + fmt.Println(encoded) + } +} + +func main() { + var b bool = true + encodeAndDecode("Boolean", b) + + var x uint8 = 42 + encodeAndDecode("Uint8", x) + + var y uint16 = 42 + encodeAndDecode("Uint16", y) + + var z uint32 = 42 + encodeAndDecode("Uint32", z) +}