0

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?

stiller_leser
  • 1,512
  • 1
  • 16
  • 39
  • You can use a generic function. Or, if you can abstract out the pieces of reconciler and ApiVerson.Kind to interfaces used in the function, you can define two interfaces for those and accept arguments of those interfaces. – Burak Serdar Apr 12 '23 at 15:24
  • "Both kinds have the same methods available." So make an interface and extract the common code into a function taking such an interface value. – Volker Apr 12 '23 at 15:24
  • Thank you for your answers. I am fairly new to go, might I ask you to provide an example? – stiller_leser Apr 12 '23 at 15:25
  • Golang does not support method overloading: May be given link will be helpful: https://stackoverflow.com/questions/23681871/golang-methods-with-same-name-and-arity-but-different-type – Pratik Mota Apr 12 '23 at 18:45

1 Answers1

0

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.

stiller_leser
  • 1,512
  • 1
  • 16
  • 39