结构体中包含结构体切片/数组
时间:2024-03-03
浏览:221
作者:佚名
大家好,我们又见面了啊~本文《结构体中包含结构体切片/数组》的内容中将会涉及到等等。如果你正在学习Golang相关知识,欢迎关注我,以后会给大家带来更多Golang相关文章,希望我们能一起进步!下面就开始本文的正式内容~
问题内容
请考虑这个 go 片段: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 结构体中表示它? (很抱歉,如果这个问题仍然含糊不清!)
解决方案
正如 @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 中的工作示例
今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
