How to use runtime.Object to create CRD generic functions in go

8/5/2018

I'm writing a Kubernetes controller in which I need to run a function over different kinds of resources, including my custom resources and other kinds of resources (This function is only interested in the resource name).

My understanding is that this is doable using runtime.Object but I can't get it to work.
Here's the function signature:

func myFunc(foo []runtime.Object) []runtime.Object

When calling the function I pass a typed object, and expect it to be assignable to runtime.Object:

foo := []v1alpha1.MyCRD{}
bar := myFunc(foo)

I'm getting compiler error:

cannot use foo (type []v1alpha1.MyCRD) as []runtime.Object in argument to myFunc

Looking at the definition of runtime.Object:

type Object interface {
  GetObjectKind() schema.ObjectKind
  DeepCopyObject() Object
}

The MyCRD type is embedding metav1.TypeMeta so it has the required GetObjectKind() function.

It is also annotated with:

// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object

So it also has the required DeepCopyObject() (which is see in the generated file).

I've been struggling with this for a while and I think it might have to do with registering the type with scheme but I'm not sure how that works, and can't find any documentation on that. I've tried copying type registration code from other projects I found without really understanding what it does (as I said, can't find docs on this).. still doesn't work.


related:

-- itaysk
client-go
go
kubernetes

0 Answers