請考慮這個 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結構中表示它?(對不起,如果這個問題仍然模棱兩可?。?
1 回答
呼啦一陣風
TA貢獻1802條經驗 獲得超6個贊
您需要一片 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中的工作示例
- 1 回答
- 0 關注
- 171 瀏覽
添加回答
舉報
0/150
提交
取消
