【问题标题】:slice/array of structs inside a struct结构内的结构切片/数组
【发布时间】:2019-05-20 21:46:50
【问题描述】:

请考虑这个 go sn-p: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 结构中表示它? (对不起,如果这个问题仍然模棱两可!)

【问题讨论】:

  • 你问的是基本语法吗?切片类型以[] 开头,所以[]Node 表示Node 的切片
  • 请拨打Tour of Go

标签: go struct


【解决方案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中的工作示例

【讨论】:

    猜你喜欢
    • 2021-12-03
    • 2012-01-27
    • 2018-06-05
    • 2015-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多