Quick actions

cmd+k|ctrl+k

Navigation

Languages

Essential Go / gob

Snippet info

Language

Go

Visibility

public

Author

kkowalczyk

Created

2019-09-19T16:52:53Z

Updated

2019-09-19T16:52:53Z

package main

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

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 main() {
     user := User{
        Username: "Angus",
        Password: "1234",
    }
    path := "user.gob"
    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())
}
INFO