Skip to content

Instantly share code, notes, and snippets.

@whyrusleeping
Created October 16, 2014 06:07
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save whyrusleeping/dda3d5f724b7fe6abbd0 to your computer and use it in GitHub Desktop.
Save whyrusleeping/dda3d5f724b7fe6abbd0 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()
}
@truongthebao
Copy link

Hi ad, can you give some advise ?
I would like to send an image through RPC and use GOB package, What should i do ?
Thanks

@rsbala
Copy link

rsbala commented Oct 5, 2017

"//This type must match exactly what youre going to be using,
// down to whether or not its a pointer" - fixed my issue. Thanks a lot

@quillaja
Copy link

quillaja commented Feb 5, 2018

Thanks. This was also helpful to me, since the examples in the standard library's documentation are somewhat deficient.

@iancarmichael
Copy link

Thanks. "Type must match exactly" seems an important point as it fixed my issue too.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment