我有一个处理资源解析的系统(将名称与文件路径匹配等)。它解析文件列表,然后保留指向返回接口(interface)实现实例的函数的指针。
更容易展示。
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
接口(interface),我只是省略了这些函数,因为它们很大并且不是我的问题的一部分。
编译这两个包时,出现以下错误:
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)
与未命名类型 func (string) *resource.Texture
不同:它们的<强> type identity 不匹配:
Two function types are identical if they have the same number of parameters and result values, corresponding parameter and result types are identical, and either both functions are variadic or neither is. Parameter and result names are not required to match.
A named and an unnamed type are always different.
即使您为函数定义了命名类型,它也不起作用:
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
不匹配:
即使一个实现了另一个的接口(interface),它们的 underlying type仍然不同):你不能 assign一对一。
您需要 NewDDSTexture()
返回 Texture
(没有指针,因为它是一个接口(interface))。
func NewDDSTexture(filename string) Texture
参见this example .
正如我在“Cast a struct pointer to interface pointer in golang”中所解释的,您通常不需要指向接口(interface)的指针。
关于interface - Go:函数回调返回接口(interface)的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27353148/