在Golang中,循环遍历数组对象并按组分组的最佳方法是什么?

9
我有一份书籍清单(BookId),每本书都与一个书籍集合(CollectionId)相关联。
我正在尝试找出按集合分组结果的最佳方法,这样属于某个集合的所有书籍都在其下列出,我可以按以下方式构建结果:
Book A、D、G属于Collection 1。 Book B、C、E属于Collection 2。
我需要循环遍历书籍列表/数组,查找它们所属的collectionID,然后需要将新列表存储如下:
CollectionID 1:
- Book A, Book D, Book G

集合编号 2:

- Book B, Book C, Book E

收藏编号 3:

- Book F

1
你能展示输入的 typeBooks 以及其他相关的数据模型吗? - leaf bebop
3个回答

10
您可以使用地图来存储每个收藏ID的书籍切片。
type Book struct {
    Title        string
    Author       string
    CollectionID int
}

func main() {
    books := GetBooks()
    collections := make(map[int][]Book)
    for _, b := range books {
        collections[b.CollectionID] = append(collections[b.CollectionID], b)
    }
    ...
}

5
首先,你需要设计你的数据库。例如:
package main

type CollectionId string

type Collection struct {
    Id   CollectionId
    Name string
}

type BookId string

type Book struct {
    Id         BookId
    Name       string
    Collection CollectionId
}

type Books map[BookId]Book

type Collections map[CollectionId][]BookId

func main() {}

同意,数据库是正确的地方来处理这个问题,而不是在内存中。 - Kenny Grant

0

Golang确实缺少一些辅助函数(例如Php中的array_map或Java中的stream),他们希望尽可能保持简单。

有一个库https://github.com/thoas/go-funk提供“现代帮助程序(map、find、contains、filter等)”,在您的情况下,您可能会对以下内容感兴趣:

ToMap

基于枢轴字段将结构体切片转换为映射。

f := &Foo{
    ID:        1,
    FirstName: "Gilles",
    LastName:  "Fabio",
    Age:       70,
}

b := &Foo{
    ID:        2,
    FirstName: "Florent",
    LastName:  "Messa",
    Age:       80,
}

results := []*Foo{f, b}

mapping := funk.ToMap(results, "ID") // map[int]*Foo{1: f, 2: b}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接