Created
October 16, 2014 06:07
-
-
Save whyrusleeping/dda3d5f724b7fe6abbd0 to your computer and use it in GitHub Desktop.
golang gob interface example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} |
"//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
Thanks. This was also helpful to me, since the examples in the standard library's documentation are somewhat deficient.
Thanks. "Type must match exactly" seems an important point as it fixed my issue too.
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
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