Skip to content

Instantly share code, notes, and snippets.

@aludvik
Last active December 5, 2017 20:24
Show Gist options
  • Save aludvik/12b816a7026850f24c0f5f64463c2902 to your computer and use it in GitHub Desktop.
Save aludvik/12b816a7026850f24c0f5f64463c2902 to your computer and use it in GitHub Desktop.
Simple go-wire interface example
package main
import (
"fmt"
"bytes"
"github.com/tendermint/go-wire"
)
type Foo interface {
Bar()
}
type A struct {
A int
}
func (_ *A) Bar() {
fmt.Println("A-Bar")
}
type B struct {
B string
}
func (_ *B) Bar() {
fmt.Println("B-Bar")
}
func CallBar(f Foo) {
foo := f.(Foo)
foo.Bar()
}
func EncodeFoo(f Foo) (*bytes.Buffer, int, error){
foo := f.(Foo)
buf, n, err := new(bytes.Buffer), int(0), error(nil)
wire.WriteBinary(foo, buf, &n, &err)
return buf, n, err
}
var _ = wire.RegisterInterface(struct{ Foo }{}, wire.ConcreteType{A{}, 0x01}, wire.ConcreteType{B{}, 0x02})
func main() {
a := &A{123}
b := &B{"123"}
// c := 5
CallBar(a)
CallBar(b)
// CallBar(c)
ba, na, erra := EncodeFoo(a)
fmt.Printf("%v, %v, %v\n", ba, na, erra)
bb, nb, errb := EncodeFoo(b)
fmt.Printf("%v, %v, %v\n", bb, nb, errb)
// EncodeFoo(c)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment