返回与接口匹配的类型的回调时出错

huangapple go评论85阅读模式
英文:

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()
    }
}

huangapple
  • 本文由 发表于 2013年7月1日 21:11:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/17405303.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定