Skip to content

Instantly share code, notes, and snippets.

@whyrusleeping
Created October 16, 2014 06:07
Show Gist options
  • 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.

@emad-elsaid
Copy link

using gob is still a pain in 2024. I tried the example in the docs, can't decode image.NRGBA into image.Image. and tried some examples from chatGPT as expected failed to solve it. then found this snippet which helped fix 2 issues:

  • I need to register &image.NRGBA.
  • and encode &image.Image not image.Image variable directly

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