转:功能回调返回接口的实现
我得到了一个处理资源解析(匹配文件路径等名称)的系统。它解析一系列文件,然后保存指向一个函数的指针,该函数返回一个接口实现的实例。转:功能回调返回接口的实现
它更容易显示。
resource.go
package resource
var (
tex_types map[string]func(string) *Texture = make(map[string]func(string) *Texture)
shader_types map[string]func(string) *Shader = make(map[string]func(string) *Shader)
)
type Texture interface {
Texture() (uint32, error)
Width() int
Height() int
}
func AddTextureLoader(ext string, fn func(string) *Texture) {
tex_types[ext] = fn
}
dds.go
package texture
type DDSTexture struct {
path string
_tid uint32
height uint32
width uint32
}
func NewDDSTexture(filename string) *DDSTexture {
return &DDSTexture{
path: filename,
_tid: 0,
height: 0,
width: 0,
}
}
func init() {
resource.AddTextureLoader("dds", NewDDSTexture)
}
DDSTexture
完全实现了Texture
接口,我只是省略了这些功能,因为他们是巨大的,而不是我的一部分题。
当编译这两个包,以下错误出现:
resource\texture\dds.go:165: cannot use NewDDSTexture (type func(string) *DDSTexture) as type func (string) *resource.Texture in argument to resource.AddTextureLoader
我将如何解决这个问题,或者这是与接口系统中的错误?只是重申:DDSTexture
完全实现resource.Texture
。
是的,DDSTexture
完全实现resource.Texture
。
但命名的类型NewDDSTexture (type func(string) *DDSTexture)
是不一样的unamed类型func (string) *resource.Texture
:他们type identity不匹配:
两个函数类型是相同的,如果他们有相同数量的参数和结果值,相应的参数和结果类型是相同的,并且这两个函数都是可变的或者都不是。参数和结果名称不需要匹配。
一个named和一个unnamed type总是不同的。
即使你定义为你的函数命名类型,它不会工作:
type FuncTexture func(string) *Texture
func AddTextureLoader(ext string, fn FuncTexture)
cannot use NewDDSTexture (type func(string) `*DDSTexture`)
as type `FuncTexture` in argument to `AddTextureLoader`
这里,结果值类型不匹配DDSTexture
与resource.Texture
:
即使一个实现另一个的界面,他们的underlying type仍然不同):你不能一个到另一个。
您需要为NewDDSTexture()
返回Texture
(无指针,因为它是一个接口)。
func NewDDSTexture(filename string) Texture
请参阅this example。
正如我在“Cast a struct pointer to interface pointer in golang”中所解释的那样,您通常不需要指向接口的指针。
我试过'NewDDSTexture()'已经返回'Texture',但是结果是:'* resource.Texture是指向接口的指针,而不是接口'。 – 2014-12-08 09:07:36
@JesseBrands权利。我从我的答案中删除了指针,并添加了一个链接到http://stackoverflow.com/a/27178682/6309,在那里我解释了你通常不需要/使用指向接口的指针。 – VonC 2014-12-08 09:12:15
谢谢你的伟大的答案,这解决了我的问题*和*现在我明白了。 – 2014-12-08 09:15:16