I have a pair of interfaces defined like so:
type Marshaler interface {
Marshal() ([]byte, error)
}
type Unmarshaler interface {
Unmarshal([]byte) error
}
I have a simple type which implement these:
type Foo struct{}
func (f *Foo) Marshal() ([]byte, error) {
return json.Marshal(f)
}
func (f *Foo) Unmarshal(data []byte) error {
return json.Unmarshal(data, &f)
}
I am using a library which defines a different interface, and implementing it like so:
func FromDb(target interface{}) { ... }
The value being passed for target
is a pointer to pointer:
fmt.Println("%T
", target) // Prints **main.Foo
Typically this function does a type switch and then operates on the type underneath. I would like to have common code for all types that implement my Unmarshaler
interface but can't figure out how to get from a pointer-to-pointer of a specific type to my interface.
You cannot define methods on a pointer to a pointer:
func (f **Foo) Unmarshal(data []byte) error {
return json.Unmarshal(data, f)
}
// compile error: invalid receiver type **Foo (*Foo is an unnamed type)
You cannot define receiver methods on pointer types:
type FooPtr *Foo
func (f *FooPtr) Unmarshal(data []byte) error {
return json.Unmarshal(data, f)
}
// compile error: invalid receiver type FooPtr (FooPtr is a pointer type)
Casting to Unmarshaler
doesn't work:
x := target.(Unmarshaler)
// panic: interface conversion: **main.Foo is not main.Unmarshaler: missing method Unmarshal
Casting to *Unmarshaler
doesn't work either:
x := target.(*Unmarshaler)
// panic: interface conversion: interface is **main.Foo, not *main.Unmarshaler
How can I get from this pointer-to-pointer type to my interface type without needing to switch on every possible implementor type?