登录
首页 >  Golang >  Go问答

在 golang 中最有效的数组对象循环和分组方法

来源:stackoverflow

时间:2024-03-28 08:18:29 253浏览 收藏

各位小伙伴们,大家好呀!看看今天我又给各位带来了什么文章?本文标题《在 golang 中最有效的数组对象循环和分组方法》,很明显是关于Golang的文章哈哈哈,其中内容主要会涉及到等等,如果能帮到你,觉得很不错的话,欢迎各位多多点评和分享!

问题内容

我有一个图书列表 (bookid),每本书都与一个图书集合 (collectionid) 关联。

我试图找出按集合对结果进行分组的最佳方法,因此属于集合的所有书籍都列在它下面,我可以通过以下方式构建结果:

书a、d、g属于收藏1。 书b、c、e属于收藏2。

我将书籍放在列表/数组中,我需要循环遍历并查找它们所属的 collectionid,并且它们需要存储新列表,如下所示:

集合 id 1:

- book a, book d, book g

集合 id 2:

- book b, book c, book e

集合 id 3:

- Book F

解决方案


您可以使用地图来存储每个馆藏 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)
    }
    ...
}

首先,设计数据库。例如,

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() {}

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>