在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
起初我讀過的部分「不可能的」,但後來回來了,卻一直運行它!好一個! –