Go suggest change

gob

Gob is a Go specific serialization method created mostly for RPC (Remote Procedure Call).

It supports all Go data types except for channels and functions.

Gob writes type information in serialized data.

It's a binary format so it's more efficient than JSON or XML.

The inclusion of type information makes encoding and decoding robust to differences between encoder and decoder.

Encode data to file and decode from file

type User struct {
    Username string
    Password string
}

func writeToGob(path string, user *User) error {
    file, err := os.Create(path)
    if err != nil {
        return err
    }

    encoder := gob.NewEncoder(file)

    err = encoder.Encode(user)
    if err != nil {
        file.Close()
        return err
    }

    return file.Close()
}

func write(path string, user *User) {
    err := writeToGob(path, user)
    if err != nil {
        log.Fatalf("writeToGob() failed with '%s'\n", err)
    }
    st, err := os.Stat(path)
    if err != nil {
        log.Fatalf("os.Stat() failed with '%s'\n", err)
    }
    fmt.Printf("Wrote user struct to file '%s' of size %d.\n", path, st.Size())
}

func read(path string) {
    user := User{}
    file, err := os.Open(path)
    if err != nil {
        log.Fatalf("os.Open('%s') failed with '%s'\n", path, err)
    }
    defer file.Close()

    decoder := gob.NewDecoder(file)
    err = decoder.Decode(&user)
    if err != nil {
        log.Fatalf("decoder.Decode() failed with '%s'\n", err)
    }
    fmt.Printf("\nRead from '%s' user:\n%#v\n", path, user)    
}

func main() {
     user := User{
        Username: "Angus",
        Password: "1234",
    }
    path := "user.gob"
    write(path, &user)
    read(path)
}
Wrote user struct to file 'user.gob' of size 62.

Read from 'user.gob' user:
main.User{Username:"Angus", Password:"1234"}

Encode an interface

package main

import (
    "encoding/gob"
    "fmt"
    "os"
)

type User struct {
    Username string
    Password string
}

type Admin struct {
    Username string
    Password string
    IsAdmin  bool
}

type Deleter interface {
    Delete()
}

func (u User) Delete() {
    fmt.Println("User ==> Delete()")
}

func (a Admin) Delete() {
    fmt.Println("Admin ==> Delete()")
}

func main() {

    user := User{
        "zola",
        "supersecretpassword",
    }

    admin := Admin{
        "john",
        "supersecretpassword",
        true,
    }

    file, _ := os.Create("user.gob")

    adminFile, _ := os.Create("admin.gob")

    defer file.Close()

    defer adminFile.Close()

    gob.Register(User{}) // registering the type allows us to encode it

    gob.Register(Admin{}) // registering the type allows us to encode it

    encoder := gob.NewEncoder(file)

    adminEncoder := gob.NewEncoder(adminFile)

    InterfaceEncode(encoder, user)

    InterfaceEncode(adminEncoder, admin)

}

func InterfaceEncode(encoder *gob.Encoder, d Deleter) {

    if err := encoder.Encode(&d); err != nil {
        fmt.Println(err)
    }
}

Decode an interface

package main

import (
    "encoding/gob"
    "fmt"
    "log"
    "os"
)

type User struct {
    Username string
    Password string
}

type Admin struct {
    Username string
    Password string
    IsAdmin  bool
}

type Deleter interface {
    Delete()
}

func (u User) Delete() {
    fmt.Println("User ==> Delete()")
}

func (a Admin) Delete() {
    fmt.Println("Admin ==> Delete()")
}

func main() {

    file, _ := os.Open("user.gob")

    adminFile, _ := os.Open("admin.gob")

    defer file.Close()

    defer adminFile.Close()

    gob.Register(User{}) // registering the type allows us to encode it

    gob.Register(Admin{}) // registering the type allows us to encode it

    var admin Deleter

    var user Deleter

    userDecoder := gob.NewDecoder(file)

    adminDecoder := gob.NewDecoder(adminFile)

    user = InterfaceDecode(userDecoder)

    admin = InterfaceDecode(adminDecoder)

    fmt.Println(user)

    fmt.Println(admin)

}

func InterfaceDecode(decoder *gob.Decoder) Deleter {

    var d Deleter

    if err := decoder.Decode(&d); err != nil {
        log.Fatal(err)
    }

    return d
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents