问题:
我在另一个结构中有一个结构映射,我想初始化结构的嵌套映射,但显然这是不可能的。
代码:
type Exporter struct {
TopicsByName map[string]Topic
}
type Topic struct {
Name string
Partitions map[int32]Partition
}
type Partition struct {
PartitionID int32
HighWaterMark int64
}
// Eventually I want to do something like:
e := Exporter{ TopicsByName: make(map[string]Topic) }
for _, topicName := range topicNames {
// This does not work because "cannot assign to struct field e.TopicsByName[topicName].Partitions in map"
e.TopicsByName[topicName].Partitions = make(map[int32]Partition)
}
// I wanted to initialize all these maps so that I can do
e.TopicsByName[x.TopicName].Partitions[x.PartitionID] = Partition{...}
我不明白为什么我无法初始化上面的嵌套结构映射。嵌套以结构体为值的 map 有那么糟糕吗?我该如何解决这个问题?
最佳答案
无法分配给映射值中的字段。解决方法是 将结构值分配给映射值:
for _, topicName := range []string{"a"} {
e.TopicsByName[topicName] = Topic{Partitions: make(map[int32]Partition)}
}
关于go - 初始化嵌套结构图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54465169/