Golang using GOB serialization of a struct object to be saved to a local

Source: Internet
Author: User

Golang can serialize struct objects through JSON or GOB, although JSON serialization is more general, but GOB encoding can be used to
It is very simple to implement the method serialization of a struct that is not supported by JSON, and it is easy to save it locally using the GOB package serialization struct.

The serialized struct object implemented by the GOB package is saved to the local

It is important to note that the Golang serialization has a small pit, that is, the field in the struct must be exportable, that is, the first letter capitalized

package mainimport (    "encoding/gob"    "fmt"    "os")type User struct {    Id   int    Name string}func (this *User) Say() string {    return this.Name + ` hello world ! `}func main(){    file, err := os.Create("mygo/gob")    if err != nil {        fmt.Println(err)    }    user := User{Id: 1, Name: "Mike"}    user2 := User{Id: 3, Name: "Jack"}    u := []User{user, user2}    enc := gob.NewEncoder(file)    err2 := enc.Encode(u)    fmt.Println(err2)}

Using GOB to deserialize local struct objects

To successfully deserialize a locally saved object, if you know the structure of a locally saved struct

package mainimport (    "encoding/gob"    "fmt"    "os")type User struct {    Id   int    Name string}func (this *User) Say() string {    return this.Name + ` hello world ! `}var u []Userfile, err := os.Open("mygo/gob")if err != nil {    fmt.Println(err)}dec := gob.NewDecoder(file)err2 := dec.Decode(&u)if err2 != nil {    fmt.Println(err2)    return}for _ , user := range u {    fmt.Println(user.Id)    fmt.Println(user.Say())}

GOB encoded serialized struct object saved to a local application I think it's a small app that needs to save the data locally so it doesn't need to be used
SQL database, you can simply deploy your app.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.