Golang中匿名界面实现
发布时间:2020-12-16 19:18:02 所属栏目:大数据 来源:网络整理
导读:在Go中,有没有办法匿名满足界面?似乎没有,但这是我最好的尝试。 (Playground) package mainimport "fmt"type Thing interface { Item() float64 SetItem(float64)}func newThing() Thing { item := 0.0 return struct { Item (func() float64) SetItem (f
在Go中,有没有办法匿名满足界面?似乎没有,但这是我最好的尝试。
(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) }
Go使用
method sets来声明属于哪一种类型的方法。只有一种方法可以使用接收器类型(方法)声明函数:
func (v T) methodName(...) ... { } 由于嵌套函数被禁止,因此无法定义匿名结构上的方法集。 第二件不允许的方法是方法是只读的。 Method values被引入允许传递方法,并在goroutines中使用它们,但不能操作方法集。 您可以做的是提供ProtoThing并引用匿名结构的底层实现(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 } 这是因为嵌入ProtoThing方法集是继承的。因此匿名结构也满足Thing接口。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |