2017-04-26 46 views
-1

我想這樣做如下:創建一個接口,其他接口的片

type Model interface { 
    EntityType() string 
    GetKey() *datastore.Key 
    SetKey(*datastore.Key) error 
    PreSave(context.Context) error 
    PostSave(context.Context) error 
    PostLoad(context.Context) error 
} 

type Models []Model interface { 
    Prepare(int) ([]Model, error) 
} 

因此struct Models也是一個接口,將由結構的片得到實現實施Model。類似以下內容:

type Foo struct { 
    key *datastore.Key `datastore:"_"` 
    // ... other things here 
} 

// assume all Model interface funcs are here and valid 

type Foos []Foo 

func (f *Foos) Prepare (num int) ([]Model, error) { 
    // do the preparations for Foo slice 
} 

顯然,上面的代碼會引發錯誤並且不可能。但是有沒有一些代碼可以產生基本相同的功能?沒有使用reflect或任何昂貴的東西?

+0

你的問題還不太清楚。請澄清「很明顯,這是不可能的」的意思。 – nos

+0

「this」表示我上面的代碼爲我拋出錯誤。編輯的問題更清晰。 – Benjam

回答

1

顯然,一個簡單的

type Models interface { 
    Prepare(int) ([]Model, error) 
} 
type Foos []Foo 
func (f Foos) Prepare(num int) ([]Model, error) { 
    // do the preparations for Foo slice 
    return nil, nil 
} 
func main() { 
    foos := Foos{} 
    models := Models(foos) 
    models.Prepare(17) 
} 

作品。

那麼你真正的問題是什麼?請參閱https://golang.org/doc/faq#covariant_typeshttps://golang.org/doc/faq#convert_slice_of_interface 這應該使它更清晰一些。

我會建議提供函數(!不是方法)來操作[]Model,而不是將模型片段抽象成更高級的類型。

+0

我想強迫'Foos'是'Model'的一部分。不僅僅是它自己的叫做'Models'的接口。該切片正被傳遞給一個函數,其中方法正在模型接口上切片中的那些元素上運行。所以我不能只是創建一個新的接口,因爲它不會成爲切片中函數的適當類型提示。 – Benjam

+0

感謝您的回答,但。我一直在查看代碼,我希望做的事情似乎不可能。 – Benjam