Go:函数回调返回接口的实现

Jes*_*nds 2 interface callback return-type return-value go

我有一个处理资源解析的系统(将名称与文件路径匹配等).它解析文件列表,然后保持指向返回接口实现实例的函数的指针.

它更容易展示.

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
}
Run Code Online (Sandbox Code Playgroud)

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)
}
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题,或者这是接口系统的错误?重申一下:DDSTexture全面实施resource.Texture.

Von*_*onC 5

是的,DDSTexture完全实现resource.Texture.

但是命名类型NewDDSTexture (type func(string) *DDSTexture)与unamed类型不同func (string) *resource.Texture:它们的类型标识不匹配:

如果两个函数类型具有相同数量的参数和结果值,相应的参数和结果类型相同,并且两个函数都是可变参数或两者都不是,则它们是相同的.参数和结果名称不需要匹配.

命名和未命名类型总是不同的.

即使您为函数定义了命名类型,它也不起作用:

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`
Run Code Online (Sandbox Code Playgroud)

这里,结果值类型DDSTextureresource.Texture以下项不匹配:
即使一个实现另一个的接口,它们的基础类型仍然不同):您不能一个分配给另一个.

你需要NewDDSTexture()返回Texture(没有指针,因为它是一个接口).

func NewDDSTexture(filename string) Texture
Run Code Online (Sandbox Code Playgroud)

这个例子.

正如我在" 在golang中转换指向接口指针的结构指针 "中所解释的那样,通常不需要指向接口的指针.