How can I type select an interface on a pointer-to-pointer in Go? -


i have pair of interfaces defined so:

type marshaler interface {     marshal() ([]byte, error) }  type unmarshaler interface {     unmarshal([]byte) error } 

i have simple type 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 using library defines different interface, , implementing so:

func fromdb(target interface{}) { ... } 

the value being passed target pointer pointer:

fmt.println("%t\n", target) // prints **main.foo 

typically function type switch , operates on type underneath. have common code types implement unmarshaler interface can't figure out how pointer-to-pointer of specific type interface.

you cannot define methods on pointer pointer:

func (f **foo) unmarshal(data []byte) error {     return json.unmarshal(data, f) } // compile error: invalid receiver type **foo (*foo 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 pointer type) 

casting unmarshaler doesn't work:

x := target.(unmarshaler) // panic: interface conversion: **main.foo not main.unmarshaler: missing method unmarshal 

casting *unmarshaler doesn't work either:

x := target.(*unmarshaler) // panic: interface conversion: interface **main.foo, not *main.unmarshaler 

how can pointer-to-pointer type interface type without needing switch on every possible implementor type?

it's ugly, is possible have semantic equivalent of pointer pointer receiver. example:

package main  import "fmt"  type p *int  type w struct{ p p }  func (w *w) foo() {         fmt.println(*w.p) }  func main() {         var p p = new(int)         *p = 42         w := w{p}         w.foo() } 

playground


output:

42 

note that

fmt.println(*w.p) 

above actually

fmt.println(*(*w).p) 

where work done compiler automagically.


Comments

Popular posts from this blog

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

html - How to style widget with post count different than without post count -

url rewriting - How to redirect a http POST with urlrewritefilter -