我想创建一个使用切片界面的函数。Go中的特定界面切片
例如我有一个接口ider
,它包含一个ID() string
函数。然后我有一个类型(Field
),它实现了ider
接口。现在我有不同的对象,其中有ider
作为参数片。
在我的功能里面,我期待一分ider
([]ider
)。该功能应该由不同类型使用,这些类型正在实施ider
。
这很难描述。因此,这里是一个完整的例子,它输出以下错误:
cannot use myObj.Fields (type []*Field) as type []ider in argument to inSlice
type ider interface {
ID() string
}
type Field struct {
Name string
}
// Implements ider interface
func (f *Field) ID() string {
return f.Name
}
type MyObject struct {
Fields []*Field
}
// uses slice of ider
func inSlice(idSlice []ider, s string) bool {
for _, v := range idSlice {
if s == v.ID() {
return true
}
}
return false
}
func main() {
fields := []*Field{
&Field{"Field1"},
}
myObj := MyObject{
Fields: fields,
}
fmt.Println(inSlice(myObj.Fields, "Field1"))
}
https://play.golang.org/p/p8PPH51vxP
我已经寻找答案,但我只是发现了空接口,而不是针对特定的人的解决方案。
可以使用idler接口来创建“fields”变量,如下所示:fields:= [] ider {{Field1}},} {}}。它运行在你去游乐场的链接。 – mgagnon
[golang:slice of struct!=它实现的接口的切片?]的可能的副本(http://stackoverflow.com/questions/12994679/golang-slice-of-struct-slice-of-interface-it-implements) –
@mgagnon是的工作。我刚刚编辑了这个问题,因为我的问题嵌套在一个附加类型中。 – apxp