dongtui9168 2015-07-11 21:30
浏览 455
已采纳

Golang中的匿名接口实现

In Go, is there a way to satisfy an interface anonymously? It doesn't seem like there is, but this was my best attempt.

(In the Playground)

package main

import "fmt"

type Thing interface {
    Item() float64
    SetItem(float64)
}

func newThing() Thing {
    item := 0.0
    return struct {
        Item (func() float64)
        SetItem (func(float64))
    }{
        Item: func() float64 { return item },
        SetItem: func(x float64) { item = x },
    }
}

func main() {
    thing := newThing()
    fmt.Println("Hello, playground")
    fmt.Println(thing)
}
  • 写回答

3条回答 默认 最新

  • duan6832168 2015-07-11 22:16
    关注

    Go uses method sets to declare which methods belong to a type. There is only one way to declare functions with receiver types (methods):

    func (v T) methodName(...) ... { }
    

    Since nested functions are forbidden, there is no way to define a method set on anonymous structs.

    The second thing that will not allow this is that methods are read-only. Method values were introduced to allow to pass methods around and use them in goroutines but not to manipulate the method set.

    What you can do instead is to provide a ProtoThing and refer to underlying implementations of your anonymous struct (on play):

    type ProtoThing struct { 
        itemMethod func() float64
        setItemMethod func(float64)
    }
    
    func (t ProtoThing) Item() float64 { return t.itemMethod() }
    func (t ProtoThing) SetItem(x float64) { t.setItemMethod(x) }
    
    // ...
    
    t := struct { ProtoThing }{}
    
    t.itemMethod = func() float64 { return 2.0 }
    t.setItemMethod = func(x float64) { item = x }
    

    This works because by embedding ProtoThing the method set is inherited. Thus the anonymous struct also satisfies the Thing interface.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 正弦信号发生器串并联电路电阻无法保持同步怎么办
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序