如何在Go语言中的map嵌套中使用for循环获取所有数据?

huangapple go评论70阅读模式
英文:

How do I get all the data in for loop in map of map in go?

问题

package main

type Stream struct {
    Labels  string
    Entries []Entry
}

type Entry struct {
    Timestamp time.Time
    Line      string
}

现在我创建了一个块的映射

chunks := make(map[string]*Stream)

我正在发送一个测试数据并尝试在这里组成我的块

for _, line := range Lines {
    fmt.Println(line.Logmsg) // 如果我在这里打印,我会得到所有的数据
    chunks["label"] = &Stream{
        Labels: "label",
        Entries: []Entry{
            Timestamp: time.Now(),
            Line:      line.Logmsg,
        },
    }
}

fmt.Println(chunks)

我在for循环中只看到最后一个数据

与第一个println相比我没有看到所有的数据我在这里做错了什么吗
英文:
package main

type Stream struct {
	Labels  string
	Entries []Entry
}

type Entry struct {
	Timestamp time.Time
	Line      string
}

now I have created a map of chunks

chunks := make(map[string]*Stream)

I am sending one test data and trying to form my chunks here

for _, line := range Lines {
	fmt.Println(line.Logmsg) // if I do print here I am getting all the data here 
	chunks["label"] = &Stream{
		Labels: "label"
		Entries: []Entry{
			Timestamp: time.Now(),
			Line:      line.Logmsg
		},
	},
}

fmt.Println(chunks) 

I am seeing the last data in the for loop here.

I am not seeing all the data compared to first println, is there anything I am doing wrong here ?

答案1

得分: 2

在地图中,所有插入的元素都在相同的键"label"下,因此最终地图中只包含一个元素。

要么为每个元素使用不同的标签,要么使用切片。

英文:

All insertions in the map are under the same key "label", so in the end the map will only contains one element.

Either use a different label for each element or use a slice.

答案2

得分: 1

你正在为所有行分配相同的映射键"label":

chunks["label"] = &Stream{...}

因此,最后一行将始终覆盖先前设置的值。这就是为什么你总是只看到最后一行。

为了使最终的chunks包含所有数据,你需要在这个映射中使用某种动态键。可以使用line的某个属性,例如:

chunks[line.Label] = &Stream{...}

我不知道你的数据,所以无法告诉你可以使用line的哪个属性。

英文:

You are assigning the stream to the same map key "label" for all lines:

chunks["label"] = &Stream{...}

Therefore the last line will always overwrite the previously set value. That is why you always only see that last line.

In order for the chunks in the end containing all data, you need to use some kind of dynamic key in this map. Something like:

chunks[line.Label] = &Stream{...}

I don't know your data so I can't tell which property you could use from line.

huangapple
  • 本文由 发表于 2021年6月8日 15:40:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/67883360.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定