我正在写一个Kubernetes控制器,监听环境自定义资源。
pkg / apis / environment / v1alpha1 / types.go 具有以下内容:
package v1alpha1
import (
meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// +genclient
// +genclient:noStatus
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// Environment describes an Environment resource
type Environment struct {
meta_v1.TypeMeta `json:",inline"`
meta_v1.ObjectMeta `json:"metadata,omitempty"`
Spec EnvironmentSpec `json:"spec"`
}
// EnvironmentSpec contains the specs for an Environment resource
type EnvironmentSpec struct {
Services []Service `json:"services"`
}
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// EnvironmentList is a list of Environment resources
type EnvironmentList struct {
meta_v1.TypeMeta `json:",inline"`
meta_v1.ListMeta `json:"metadata"`
Items []Environment `json:"items"`
}
// Service describes a Service in the Environment Custom Resource
type Service struct {
Code string `json:"code"`
Parameters struct {
Foo map[string]string `json:"foo"`
Bar int `json:"bar"`
} `json:"parameters"`
}
运行k8s.io/code-generator/generate-groups.sh脚本后,我最终遇到一个错误的 pkg / apis / environment / v1alpha1 / zz_generation.deepcopy.go 文件。问题来自此生成的方法:
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *Service) DeepCopyInto(out *Service) {
*out = *in
in.Parameters.DeepCopyInto(&out.Parameters)
return
}
尝试构建或运行此代码将给我以下错误
pkg/apis/environment/v1alpha1/zz_generated.deepcopy.go:113:15: in.Parameters.DeepCopyInto undefined (type struct { Foo map[string]string "json:\"foo\""; Bar int "json:\"bar\"" } has no field or method DeepCopyInto)
一旦在 Parameters 结构中包含的匿名结构中有一个 Map 或 Slice ,我就会遇到此错误。 / p>
WORKAROUND
一种解决方法是创建一个将包含地图的命名类型。例如,我重构了 Service 结构,如下所示:
// Service describes a Service in the Environment Custom Resource
type Service struct {
Code string `json:"code"`
Parameters FooBar `json:"parameters"`
}
type FooBar struct {
Foo map[string]string `json:"foo"`
Bar int `json:"bar"`
}
生成的func (in *Service) DeepCopyInto(out *Service)
不变,但是创建了以下2种新方法:
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *FooBar) DeepCopyInto(out *FooBar) {
*out = *in
if in.Foo != nil {
in, out := &in.Foo, &out.Foo
*out = make(map[string]string, len(*in))
for key, val := range *in {
(*out)[key] = val
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new FooBar.
func (in *FooBar) DeepCopy() *FooBar {
if in == nil {
return nil
}
out := new(FooBar)
in.DeepCopyInto(out)
return out
}
现在,我在构建和运行代码方面没有任何问题。
这种解决方法很痛苦,因为我真正的 Service 结构比本示例中的要大得多。
是否可以通过代码生成器在匿名函数内部使用映射和切片?