Search⌘ K

Solution Review: Decode the Contents

Explore how to decode gob data stored in a file using Go's file handling and decoder methods. Understand the process of opening files, managing errors, and converting binary data back to structured Go types effectively.

We'll cover the following...
Go (1.6.2)
package main
import (
"bufio"
"fmt"
"encoding/gob"
"log"
"os"
)
type Address struct {
Type string
City string
Country string
}
type VCard struct {
FirstName string
LastName string
Addresses []*Address
Remark string
}
var content string
var vc VCard
func main() {
// using a decoder:
file, _ := os.Open("vcard.gob")
defer file.Close()
inReader := bufio.NewReader(file)
dec := gob.NewDecoder(inReader)
err := dec.Decode(&vc)
if err != nil {
log.Println("Error in decoding gob")
}
fmt.Println(vc)
}

This is the inverse from the code example in the previous lesson: we have a file vcard.gob ...