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条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器