英文:
Error when returning callback which returns type matching interface
问题
以下是翻译好的部分:
在play.golang.org上的错误示例:http://play.golang.org/p/GRoqRHnTj6
以下代码返回一个错误信息:"prog.go:16: cannot use NewMyGame (type func() MyGame) as type func() Playable in return argument",尽管接口是完全空的。请参见下面附上的代码,不幸的是我完全被困住了,非常感谢任何帮助。
package main
// 定义一个任意游戏类型
type MyGame struct{}
// 为任意游戏类型创建一个构造函数
func NewMyGame() MyGame {
return MyGame{}
}
// 定义一个定义游戏类型的接口
type Playable interface{}
// 在我的应用程序中,它将返回与接口匹配的构造函数列表
func Playables() func() Playable {
return NewMyGame
}
func main() {}
英文:
Example of error @ play.golang.org: http://play.golang.org/p/GRoqRHnTj6
The following code is returning a "prog.go:16: cannot use NewMyGame (type func() MyGame) as type func() Playable in return argument" even though the interface is completely empty. Please find code attached below too, I'm completely stumped unfortunately and any help would be hugely appreciated.
package main
// Define an arbitrary game type
type MyGame struct{}
// Create a constructor function for arbitrary game type
func NewMyGame() MyGame {
return MyGame{}
}
// Define an interface defining game types
type Playable interface{}
// In my app it will return a list of constructors matching interface
func Playables() func() Playable {
return NewMyGame
}
func main() {}
答案1
得分: 1
这是错误提示的确切内容:
无法将NewMyGame(类型为func() MyGame)用作func() Playable类型
一个简单的修复方法是:
func Playables() func() Playable {
return func() (Playable) {
return NewMyGame()
}
}
英文:
It's exactly as the error says,
cannot use NewMyGame (type func() MyGame) as type func() Playable
A simple fix would be
func Playables() func() Playable {
return func() (Playable) {
return NewMyGame()
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论