I have created a map with the following structure:
m := make(map[int]Record)
The Record is a struct as follows:
type Record struct {
UID int
Type string
Year string
}
The SumRecord struct is supposed to store information about the number of occurences of every given Type / Year Value in map m.
type SumRecord struct {
Sum int
Type string
Year string
}
The struct is supposed to hold information about book publication years, ie {1, "Type": "fiction", "Year": 1996}, {2, "Type": "non-fiction", "Year": 1996}
I am unsuccessfully trying to create a second map where I would store the sum of each publication type per year (similar to a SUM / GROUP BY in SQL). How can I achieve that with Go?
Here's an alternative solution to the one provided by @ThunderCat.
This creates a new mapping of a SumRecord to an integer, representing the sum of occurrences for that specific grouping of Type/Year.
See full example here.
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",
}])