英文:
MissingListField when assign struct literal to node
问题
我正在尝试创建一个k8s节点结构并为其分配默认值。
以下代码报错:"在结构体字面量中未知的字段 Name"
node = &corev1.Node{Name: pod.Spec.NodeName}
然而,这段代码是正确的:
node = &corev1.Node{}
node.Name = pod.Spec.NodeName
为什么会这样呢?
英文:
I'm trying to create a k8s node struct and assign default value to it.
The following code complains "unknown field Name in struct literal"
node = &corev1.Node{Name: pod.Spec.NodeName}
However, this code is fine:
node = &corev1.Node{}
node.Name = pod.Spec.NodeName
why?
答案1
得分: 1
如果第二段代码有效,我会认为存在一个嵌入的结构体,并且根据代码(假设是这个),看起来是这种情况:
type Node struct {
metav1.TypeMeta `json:",inline"`
// 标准对象的元数据。
// 更多信息:https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
// +optional
metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`
// Spec 定义了节点的行为。
// https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
// +optional
Spec NodeSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"`
// 节点的最近观察到的状态。
// 由系统填充。
// 只读。
// 更多信息:https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
// +optional
Status NodeStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"`
}
因此,name字段很可能是metav1.TypeMeta
或metav1.ObjectMeta
的一部分,在更深层次中发现它在ObjectMeta上,这意味着要定义内联,你需要这样做:
package main
import (
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// ...
node := &corev1.Node{ObjectMeta: metav1.ObjectMeta{Name: pod.Spec.NodeName}}
英文:
If the second code works, I'd assume there is an embedded struct, and looking at the code (assuming it's this) that appears to be the case:
type Node struct {
metav1.TypeMeta `json:",inline"`
// Standard object's metadata.
// More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
// +optional
metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`
// Spec defines the behavior of a node.
// https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
// +optional
Spec NodeSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"`
// Most recently observed status of the node.
// Populated by the system.
// Read-only.
// More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
// +optional
Status NodeStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"`
}
So the name field is likely either part of metav1.TypeMeta
, or metav1.ObjectMeta
, digging deeper it's on ObjectMeta, which means to define inline, you'll need to do something like:
package main
import (
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// ...
node := &corev1.Node{ObjectMeta: metav1.ObjectMeta{ Name: pod.Spec.NodeName}}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论