在Go中,有没有一种方法可以匿名满足接口?它似乎并不存在,但这是我最好的尝试。Golang中的匿名接口实现
(在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)
}
这实在是真棒,我喜欢它是如何半结构化的。嵌入是非常整洁。 – jocull
起初我读过的部分“不可能的”,但后来回来了,却一直运行它!好一个! –