Skip to content

Commit

Permalink
Example #21: serializing basic data types into gob format
Browse files Browse the repository at this point in the history
  • Loading branch information
tisnik committed Jul 3, 2020
1 parent 8be6025 commit 6c6b293
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions lesson7/marshalling/21_gob_marshal_basic_types.go
Original file line number Diff line number Diff line change
@@ -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)
}

0 comments on commit 6c6b293

Please sign in to comment.