猿问

结构内的结构切片/数组

请考虑这个 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结构也有/保留一个节点列表。或者,由于这是 Go,所以是一片结构,我如何在Service结构中表示它?(对不起,如果这个问题仍然模棱两可!)


凤凰求蛊
浏览 126回答 1
1回答

呼啦一阵风

您需要一片 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 objectsnodes := []Node{}// append each Node to the slice of Node objectsnodes = append(nodes, Node1, Node2, Node3)// include the slice of Node objects to the Service object during initializationmyService := Service{"PotatoServer", 3, Node1, true, nodes}查看playground中的工作示例
随时随地看视频慕课网APP

相关分类

Go
我要回答