我有一對這樣定義的接口:type Marshaler interface { Marshal() ([]byte, error)}type Unmarshaler interface { Unmarshal([]byte) error}我有一個實現這些的簡單類型: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)}我正在使用一個定義不同接口的庫,并像這樣實現它:func FromDb(target interface{}) { ... }傳遞的值target是一個指向指針的指針:fmt.Println("%T\n", target) // Prints **main.Foo通常,此函數執行類型切換,然后對下面的類型進行操作。我想擁有實現我的Unmarshaler接口的所有類型的通用代碼,但無法弄清楚如何從特定類型的指針到我的接口。您不能在指向指針的指針上定義方法:func (f **Foo) Unmarshal(data []byte) error { return json.Unmarshal(data, f)}// compile error: invalid receiver type **Foo (*Foo is an unnamed type)您不能在指針類型上定義接收器方法:type FooPtr *Foofunc (f *FooPtr) Unmarshal(data []byte) error { return json.Unmarshal(data, f)}// compile error: invalid receiver type FooPtr (FooPtr is a pointer type)投射到Unmarshaler不起作用:x := target.(Unmarshaler)// panic: interface conversion: **main.Foo is not main.Unmarshaler: missing method Unmarshal投射到*Unmarshaler也不起作用:x := target.(*Unmarshaler)// panic: interface conversion: interface is **main.Foo, not *main.Unmarshaler我怎樣才能從這個指針到指針類型獲得我的接口類型而不需要打開每個可能的實現者類型?
- 2 回答
- 0 關注
- 183 瀏覽
添加回答
舉報
0/150
提交
取消