What is the purpose of the gob.Register method?

I read the documentation (gob) and I have some problems:

Now I know how to encode the structure and decode like this:

func main() {
s1 := &S{
    Field1: "Hello Gob",
    Field2: 999,
}
log.Println("Original value:", s1)
buf := new(bytes.Buffer)
err := gob.NewEncoder(buf).Encode(s1)
if err != nil {
    log.Println("Encode:", err)
    return
}

s2 := &S{}
err = gob.NewDecoder(buf).Decode(s2)
if err != nil {
    log.Println("Decode:", err)
    return
}
log.Println("Decoded value:", s2)

}

But I do not know the purpose of this method, gob.Register()can someone explain to me when to use it and why?

+6
source share
2 answers

If you are dealing only with specific types (structures), you really do not need it. Once you come across interfaces, you must first register your specific type.

For example, suppose we have such a structure and interface (the structure implements the interface):

type Getter interface {
    Get() string
}


type Foo struct {
    Bar string
}

func (f Foo)Get() string {
    return f.Bar
}

Foo gob Getter ,

gob.Register(Foo{})

, :

// init and register
buf := bytes.NewBuffer(nil)
gob.Register(Foo{})    


// create a getter of Foo
g := Getter(Foo{"wazzup"})

// encode
enc := gob.NewEncoder(buf)
enc.Encode(&g)

// decode
dec := gob.NewDecoder(buf)
var gg Getter
if err := dec.Decode(&gg); err != nil {
    panic(err)
}

Register, , gob , .

+6

Source: https://habr.com/ru/post/1608192/


All Articles