I want to create a function, which uses a slice of an interface.
For example I have an interface ider
which wraps one ID() string
function. Then I have a type (Field
), which implements the ider
interface. Now I have different objects, which have slice of ider
as parameter.
Inside my function I expect a slice of ider
([]ider
). That function should be used by different types, which are implementing the ider
.
This is hard to describe. So here is a complete example, which outputs the following error:
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
I already searched for answers, but I did just found solutions for empty interfaces and not for specific ones.