我得到了一個處理資源解析(匹配文件路徑等名稱)的系統。它解析一系列文件,然後保存指向一個函數的指針,該函數返回一個接口實現的實例。轉:功能回調返回接口的實現
它更容易顯示。
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
。
我試過'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