2014-12-08 68 views
2

我得到了一個處理資源解析(匹配文件路徑等名稱)的系統。它解析一系列文件,然後保存指向一個函數的指針,該函數返回一個接口實現的實例。轉:功能回調返回接口的實現

它更容易顯示。

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

回答

5

是的,DDSTexture完全實現resource.Texture

但命名的類型NewDDSTexture (type func(string) *DDSTexture)是不一樣的unamed類型func (string) *resource.Texture:他們type identity不匹配:

兩個函數類型是相同的,如果他們有相同數量的參數和結果值,相應的參數和結果類型是相同的,並且這兩個函數都是可變的或者都不是。參數和結果名稱不需要匹配。

一個named和一個unnamed type總是不同的。

即使你定義爲你的函數命名類型,它不會工作:

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
即使一個實現另一個的界面,他們的underlying type仍然不同):你不能一個到另一個。

您需要爲NewDDSTexture()返回Texture(無指針,因爲它是一個接口)。

func NewDDSTexture(filename string) Texture 

請參閱this example

正如我在「Cast a struct pointer to interface pointer in golang」中所解釋的那樣,您通常不需要指向接口的指針。

+0

我試過'NewDDSTexture()'已經返回'Texture',但是結果是:'* resource.Texture是指向接口的指針,而不是接口'。 – 2014-12-08 09:07:36

+0

@JesseBrands權利。我從我的答案中刪除了指針,並添加了一個鏈接到http://stackoverflow.com/a/27178682/6309,在那裏我解釋了你通常不需要/使用指向接口的指針。 – VonC 2014-12-08 09:12:15

+0

謝謝你的偉大的答案,這解決了我的問題*和*現在我明白了。 – 2014-12-08 09:15:16