Dictionary 如何使用Golang计算地图中某个值的出现次数?

Dictionary 如何使用Golang计算地图中某个值的出现次数?,dictionary,go,sum,Dictionary,Go,Sum,我已创建具有以下结构的地图: m := make(map[int]Record) 该记录是一个结构,如下所示: type Record struct { UID int Type string Year string } SumRecord结构应该在map m中存储关于每个给定类型/年份值的发生次数的信息 type SumRecord struct { Sum int Type string Year string } 该结构应该保存有关

我已创建具有以下结构的地图:

m := make(map[int]Record)
该记录是一个结构,如下所示:

type Record struct {
    UID  int
    Type string
    Year string
}
SumRecord结构应该在map m中存储关于每个给定类型/年份值的发生次数的信息

type SumRecord struct {
    Sum  int
    Type string
    Year string
}
该结构应该保存有关图书出版年份的信息,即
{1,“类型”:“虚构”,“年份”:1996},{2,“类型”:“非虚构”,“年份”:1996}


我试图创建第二个映射,在其中存储每年每种发布类型的总和(类似于SQL中的sum/GROUP BY),但未成功。使用Go如何实现这一点?

这里有一个替代@ThunderCat提供的解决方案

这将创建SumRecord到整数的新映射,表示特定类型/年份分组的事件总数

请参阅完整示例


map
map[int]记录中的键是什么,还是不重要?第二张地图上的钥匙是什么?是(年份,类型)?
map[int]Record
中的键只是一个计数器(记录条目来自代码早期解析的xml),因此它并不重要。对于第二个映射,键应该是year,type(SumRecord
struct)。
type Record struct {
    UID  int
    Type string
    Year string
}

type SumRecord struct {
    Type string
    Year string
}

m := make(map[int]Record)

// e.g. [{"1996","non-fiction"}:4], representing 4 occurrences of {"1996","non-fiction"}
srMap := make(map[SumRecord]int)

// add records

// loop over records
for key := range m {
    sr := SumRecord{
        Type: m[key].Type,
        Year: m[key].Year,
    }
    // creates new counter or increments existing pair counter by 1
    srMap[sr] += 1
}
// print all mappings
fmt.Println(srMap)

// specific example
fmt.Println(srMap[SumRecord{
    Year: "1996",
    Type: "non-fiction",
}])