2017-04-26 44 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