亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

來自我的包外部的結構的多態性

來自我的包外部的結構的多態性

Go
滄海一幻覺 2022-09-26 17:26:10
我正在嘗試構建一個方法,該方法使用 Kubernetes 客戶端 go 庫,獲取并返回給定 .我有這個:*metav1.OwnerReferencefunc fetchResource(ref *metav1.OwnerReference, options *RequestOptions) (*metav1.ObjectMeta, error) {    switch ref.Kind {    case "ReplicaSet":        return options.Clientset.AppsV1().ReplicaSets(options.Namespace).Get(options.Context, ref.Name, metav1.GetOptions{})    case "Deployment":        return options.Clientset.AppsV1().Deployments(options.Namespace).Get(options.Context, ref.Name, metav1.GetOptions{})    case "Job":        fallthrough    // more stuff...    default:        return nil, nil    }}此代碼無法編譯,因為:不能使用選項。Clientset.AppsV1().ReplicaSets(選項。命名空間)。獲取(選項。上下文,引用。名稱, (元 v1.獲取選項文本))(類型為 *“k8s.io/api/apps/v1”的值。副本集) 為 *“k8s.io/apimachinery/pkg/apis/meta/v1”。返回語句中的對象Meta值我的猜測是,由于文檔說基本上所有資源都嵌入了 ,我可以將其用作返回類型。metav1.ObjectMeta我嘗試創建并返回一個,但意識到我無法為包外的類型實現它:interfacetype K8sResource interface {    Name() string    Kind() string    OwnerReferences() []metav1.OwnerReference}func (pod *corev1.Pod) Name() string {    return pod.Name}func (pod *corev1.Pod) Kind() string {    return pod.Kind}func (pod *corev1.Pod) OwnerReferences() []metav1.OwnerReference {    return pod.OwnerReferences}此代碼無法編譯,因為:無效的接收器 *“k8s.io/api/core/v1”。Pod(此包中未定義的類型)這里的慣用和正確的解決方案是什么?
查看完整描述

1 回答

?
慕工程0101907

TA貢獻1887條經驗 獲得超5個贊

如果要將導入的類型作為接口返回,而這些類型尚未實現,則可以將它們包裝在實現它的類型中。


例如:


type K8sResource interface {

    Name() string

    Kind() string

    OwnerReferences() []metav1.OwnerReference

}

type replicaSet struct{ *v1.ReplicaSet }


func (s replicaSet) Name() string {

    return s.ReplicaSet.Name

}

func (s replicaSet) Kind() string {

    return s.ReplicaSet.Kind

}

func (s replicaSet) OwnerReferences() []metav1.OwnerReference {

    return s.ReplicaSet.OwnerReferences

}

func fetchResource(ref *metav1.OwnerReference, options *RequestOptions) (K8sResource, error) {

    switch ref.Kind {

    case "ReplicaSet":

        res, err := options.Clientset.AppsV1().ReplicaSets(options.Namespace).Get(options.Context, ref.Name, metav1.GetOptions{})

        if err != nil {

            return nil, err

        }

        return replicaSet{res}, nil // wrap it up

    case "Pod":

        res, err := options.Clientset.AppsV1().Pods(options.Namespace).Get(options.Context, ref.Name, metav1.GetOptions{})

        if err != nil {

            return nil, err

        }

        return pod{res}, nil // wrap it up

    case "Job":

        fallthrough

    // more stuff...

    default:

        return nil, nil

    }

}


查看完整回答
反對 回復 2022-09-26
  • 1 回答
  • 0 關注
  • 84 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號