结构内部的结构切片/数组

时间:2019-05-20 21:46:51

标签: go struct

请考虑以下示例:https://play.golang.org/p/JkMIRwshG5U

我的Service结构保持:

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

并且我的Node结构具有:

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

假设我的服务有3个节点;我希望Service结构也具有/保留节点列表。或者,因为这是Go,所以要分割一片结构,如何在Service结构中表示它呢? (很抱歉,这个问题是否仍然存在歧义!)

1 个答案:

答案 0 :(得分:1)

正如@JimB指出的那样,您需要一片Node对象。只需在Service结构中创建一个新字段来存储一个Node对象切片,然后将每个Node对象附加到该Node对象切片。

对您的代码进行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}

playground

中查看有效的示例
相关问题