英文:
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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论