在Go中,有没有办法匿名满足接口?似乎没有,但这是我最好的尝试。
(In the 操场 http://play.golang.org/p/4i-8o087dg)
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)
}
Go uses 方法集 http://golang.org/ref/spec#Method_sets声明哪些方法属于某个类型。只有一种方法可以声明具有接收者类型(方法)的函数:
func (v T) methodName(...) ... { }
由于嵌套函数是被禁止的,因此无法在匿名结构上定义方法集。
第二件事不允许这样做是方法是只读的。方法值 http://golang.org/ref/spec#Method_values引入是为了允许传递方法并在 goroutine 中使用它们,但不允许操作方法集。
相反,您可以做的是提供 ProtoThing 并引用匿名结构的底层实现(on play http://play.golang.org/p/k0lCJqyF6p):
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 }
这是有效的,因为通过嵌入ProtoThing
方法集是继承的。因此匿名结构也满足Thing
界面。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)