结构内的结构切片/阵列



请考虑此GO代码:https://play.golang.org/p/jkmirwshg5u

我的Service结构保持:

type Service struct {
    ServiceName string
    NodeCount   int
    HeadNode    Node
    Health      bool
}

我的节点结构:

type Node struct {
    NodeName  string
    LastHeard int
    Role      bool
    Health    bool
}

假设我有3个节点用于我的服务;我希望Service struct还具有/保留一个节点列表。或者,由于这是一定的,因此如何在Service struct中表示此片段?(对不起,如果这个问题仍然含糊不清!(

正如@jimb指出的那样,您需要一片节点对象。只需在服务结构中创建一个新字段即可存储一个节点对象,然后将每个节点对象附加到节点对象的片段。

4个次要编辑您的代码:

type Service struct {
    ServiceName string
    NodeCount   int
    HeadNode    Node
    Health      bool
    // include Nodes field as a slice of Node objects
    Nodes       []Node
}
// local variable to hold the slice of Node objects
nodes := []Node{}
// append each Node to the slice of Node objects
nodes = append(nodes, Node1, Node2, Node3)
// include the slice of Node objects to the Service object during initialization
myService := Service{"PotatoServer", 3, Node1, true, nodes}

请参阅操场上的一个工作示例

最新更新