Skip to content

Instantly share code, notes, and snippets.

@benjiqq
Forked from udhos/gob.go
Created February 7, 2020 22:03
Show Gist options
  • Save benjiqq/3b4cb7ef8f6d7a7f5eba1d2784711f63 to your computer and use it in GitHub Desktop.
Save benjiqq/3b4cb7ef8f6d7a7f5eba1d2784711f63 to your computer and use it in GitHub Desktop.
golang gob interface example
package main
import (
"bytes"
"encoding/gob"
"fmt"
)
type MyFace interface {
A()
}
type Cat struct{}
type Dog struct{}
func (c *Cat) A() {
fmt.Println("Meow")
}
func (d *Dog) A() {
fmt.Println("Woof")
}
func init() {
// This type must match exactly what youre going to be using,
// down to whether or not its a pointer
gob.Register(&Cat{})
gob.Register(&Dog{})
}
func main() {
network := new(bytes.Buffer)
enc := gob.NewEncoder(network)
var inter MyFace
inter = new(Cat)
// Note: pointer to the interface
err := enc.Encode(&inter)
if err != nil {
panic(err)
}
inter = new(Dog)
err = enc.Encode(&inter)
if err != nil {
panic(err)
}
// Now lets get them back out
dec := gob.NewDecoder(network)
var get MyFace
err = dec.Decode(&get)
if err != nil {
panic(err)
}
// Should meow
get.A()
err = dec.Decode(&get)
if err != nil {
panic(err)
}
// Should woof
get.A()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment