gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 01:33:45 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com