亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 Go 中的指針到指針上鍵入選擇接口?

如何在 Go 中的指針到指針上鍵入選擇接口?

Go
慕容708150 2021-06-20 16:12:17
我有一對這樣定義的接口: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 回答

  • 2 回答
  • 0 關注
  • 183 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號