golang里如何实现多态?
以下代码来自kubernetes:
// TODO: move this, Object, List, and Type to a different package
// ObjectMetaAccessor 接口是所有GVK都要实现的,当然包括最常用的Deployment
type ObjectMetaAccessor interface {
// 获取GVK对象的元信息(命名空间,创建时间 etc.)
GetObjectMeta() Object
}
ObjectMetaAccessor
- deployment.go
// Deployment enables declarative updates for Pods and ReplicaSets.
type Deployment struct {
metav1.TypeMeta `json:",inline"`
// Standard object metadata.
// (1) 可以发现:只声明了类型metav1.ObjectMeta
// 而没有声明字段变量(e.g. metadata metav1.ObjectMeta)。
metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`
// Specification of the desired behavior of the Deployment.
// +optional
Spec DeploymentSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"`
// Most recently observed status of the Deployment.
// +optional
Status DeploymentStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"`
}
(1)Deploymentmetav1.ObjectMetametav1.ObjectMeta
DeploymentGetObjectMeta()Deploymentmetav1.ObjectMeta
也就是说实际调用的是这个方法: