gokuberneteskubebuilder

Method re-use in go code using controller-runtime


I need help with method re-usage in Go.

I have two function signatures in my Kubernetes operator (in different controllers):

func myFunc(ctx context.Context, r *MyKindReconciler, myKind *myApiVersion.myKind) (ctrl.Result, error) {

and

func myFunc(ctx context.Context, r *MyOtherKindReconciler, myOtherKind *myApiVersion.myOtherKind) (ctrl.Result, error) {

The body of the function myFunc is the same in both cases, only the types of the variables that are passed in are different. Both kinds have the same methods available.

In order to prevent duplication, I’d like to move this method to a helper if possible. Any idea how this can be achieved?


Solution

  • Got it to work.

    Here's the interace I build:

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

    A potential method signature looks like this:

    func myFunc(ctx context.Context, client client.Client, object MyObject){}
    

    Only downside .DeepCopy() will not be available as it returns a specific type and can't be overloaded in the Interface.