interface - Go:函数回调返回接口(interface)的实现

标签 interface go callback return-value return-type

我有一个处理资源解析的系统(将名称与文件路径匹配等)。它解析文件列表,然后保留指向返回接口(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`

此处,结果值类型与 DDSTextureresource.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/

相关文章:

c# - 如何在不使用反射的情况下获取类中指定类型的所有属性

android - loginButton.registerCallback 无法解析方法

jquery - 为什么需要 e.preventDefault

go - 如何将文件行中的值分配给 Golang 中的 map

string - 在 go 中查找行数的最快方法?

ios - RemoteIO AudioUnit 播放质量与回调运行时无关,而是与其他因素相关

java - 如何向多个类继承的方法添加参数

pointers - 动态参数和通用类型

java - 如何使用实例变量隐藏接口(interface)变量

json - 在 UnmarshalJSON 函数中调用 json.Unmarshal 不会导致堆栈溢出