在Go代码中使用controller-runtime进行方法重用

huangapple go评论86阅读模式
英文:

Method re-use in go code using controller-runtime

问题

我需要帮助解决Go语言中的方法重用问题。

我在我的Kubernetes操作员中有两个函数签名(在不同的控制器中):

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

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

这两个函数的函数体是相同的,只是传入的变量类型不同。这两个"kind"都有相同的可用方法。

为了避免重复,我想将这个方法移到一个辅助函数中。有什么办法可以实现这个目标吗?

英文:

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?

答案1

得分: 0

明白了,以下是翻译好的内容:

成功解决了。

这是我构建的接口:

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

一个可能的方法签名如下:

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

唯一的缺点是.DeepCopy()方法将不可用,因为它返回一个特定类型,并且无法在接口中进行重载。

英文:

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.

huangapple
  • 本文由 发表于 2023年4月12日 23:20:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/75997190.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定