搜索
首页后端开发Golang如何根据 Golang 中的特定字段对结构体切片进行有效分组和求和?

How can I efficiently group and sum a slice of structs based on specific fields in Golang?

Golang 中结构体切片的高效分组与求和

在 Golang 中,高效处理数据至关重要。在处理结构体切片时,分组和求和等任务可能会变得具有挑战性。本指南提出了一种根据特定字段对结构体切片进行分组和求和的有效方法。

问题陈述

考虑以下结构:

type Register struct {
    id1 int
    id2 int
    id3 int
    id4 int
    id5 int
    id6 int
    id7 int
    id8 int
    money int
}

目标是按字段 id1、id2、id3、id4、id5、id6、id7 和 id8 对寄存器进行分组,然后对关联的 Money 字段求和。

解决方案

提供的解决方案涉及对结构类型的轻微重构。通过将关键字段提取到单独的结构体 Key 中,我们可以利用 Golang 中结构体的可比性。

重构类型

type Key struct {
    id1 int
    id2 int
    id3 int
    id4 int
    id5 int
    id6 int
    id7 int
    id8 int
}

type Register struct {
    key   Key
    money int
}

分组和求和

为了实现分组和求和,我们创建一个map[Key]int。地图的Key代表id字段的组合,value代表同一个key的寄存器的金额总和。

regs := []*Register{
    {Key{id1: 345}, 1500},
    {Key{id1: 345, id2: 140}, 2700},
    {Key{id1: 345, id2: 140}, 1300},
    {Key{id1: 345}, 1000},
    {Key{id3: 999}, 1000},
    {Key{id3: 999}, 2000},
}

// calculate sum:
m := map[Key]int{}
for _, v := range regs {
    m[v.key] += v.money
}

输出

map 提供寄存器的分组和求和表示。

map[{345 0 0 0 0 0 0 0}:2500 {345 140 0 0 0 0 0 0}:4000 {0 0 999 0 0 0 0 0}:3000]

增强输出

为了提高可读性,我们可以按如下方式格式化输出:

fmt.Println("Nice output:")
for k, v := range m {
    fmt.Printf("%+3v: %d\n", k, v)
}

结果

Nice output:
{id1:345 id2:  0 id3:  0 id4:  0 id5:  0 id6:  0 id7:  0 id8:  0}: 2500
{id1:345 id2:140 id3:  0 id4:  0 id5:  0 id6:  0 id7:  0 id8:  0}: 4000
{id1:  0 id2:  0 id3:999 id4:  0 id5:  0 id6:  0 id7:  0 id8:  0}: 3000

优点

这种方法有几个优点:

  • 简化使用映射进行分组和求和
  • 通过利用可比结构有效处理数据
  • 通过使用 Key 结构灵活处理不同的分组标准

以上是如何根据 Golang 中的特定字段对结构体切片进行有效分组和求和?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
在GO应用程序中有效记录错误在GO应用程序中有效记录错误Apr 30, 2025 am 12:23 AM

有效的Go应用错误日志记录需要平衡细节和性能。1)使用标准log包简单但缺乏上下文。2)logrus提供结构化日志和自定义字段。3)zap结合性能和结构化日志,但需要更多设置。完整的错误日志系统应包括错误enrichment、日志级别、集中式日志、性能考虑和错误处理模式。

go中的空接口(接口{}):用例和注意事项go中的空接口(接口{}):用例和注意事项Apr 30, 2025 am 12:23 AM

EmptyinterfacesinGoareinterfaceswithnomethods,representinganyvalue,andshouldbeusedwhenhandlingunknowndatatypes.1)Theyofferflexibilityforgenericdataprocessing,asseeninthefmtpackage.2)Usethemcautiouslyduetopotentiallossoftypesafetyandperformanceissues,

比较并发模型:GO与其他语言比较并发模型:GO与其他语言Apr 30, 2025 am 12:20 AM

go'sconcurrencyModelisuniqueduetoItsuseofGoroutinesandChannels,offeringaleightweightandefficePparreactComparredTothread-likeModelsInlanguagesLikeLikejava,python,andrust.1)

GO的并发模型:解释的Goroutines和频道GO的并发模型:解释的Goroutines和频道Apr 30, 2025 am 12:04 AM

go'sconcurrencyModeluessgoroutinesandChannelStomanageConconCurrentPrommmengement.1)GoroutinesArightweightThreadThreadSthAtalLeadSthAtalAlaLeasyParalleAftasks,增强Performance.2)ChannelsfacilitatesfacilitatesafeDataTaAexafeDataTaAexchangeBetnegnegoroutinesGoroutinesGoroutinesGoroutinesGoroutines,crucialforsforsynchrroniz

GO中的接口和多态性:实现代码可重复使用性GO中的接口和多态性:实现代码可重复使用性Apr 29, 2025 am 12:31 AM

Interfaceand -polymormormormormormingingoenhancecodereusability and Maintainability.1)DewineInterfaceSattherightabStractractionLevel.2)useInterInterFacesForceFordEffeldIndentientIndoction.3)ProfileCodeTomanagePerformanceImpacts。

'初始化”功能在GO中的作用是什么?'初始化”功能在GO中的作用是什么?Apr 29, 2025 am 12:28 AM

TheinitfunctioninGorunsautomaticallybeforethemainfunctiontoinitializepackagesandsetuptheenvironment.It'susefulforsettingupglobalvariables,resources,andperformingone-timesetuptasksacrossanypackage.Here'showitworks:1)Itcanbeusedinanypackage,notjusttheo

GO中的界面组成:构建复杂的抽象GO中的界面组成:构建复杂的抽象Apr 29, 2025 am 12:24 AM

接口组合在Go编程中通过将功能分解为小型、专注的接口来构建复杂抽象。1)定义Reader、Writer和Closer接口。2)通过组合这些接口创建如File和NetworkStream的复杂类型。3)使用ProcessData函数展示如何处理这些组合接口。这种方法增强了代码的灵活性、可测试性和可重用性,但需注意避免过度碎片化和组合复杂性。

在GO中使用Init功能时的潜在陷阱和考虑因素在GO中使用Init功能时的潜在陷阱和考虑因素Apr 29, 2025 am 12:02 AM

initfunctionsingoareAutomationalCalledBeLedBeForeTheMainFunctionandAreuseFulforSetupButcomeWithChallenges.1)executiondorder:totiernitFunctionSrunIndIndefinitionorder,cancancapationSifsUsiseSiftheyDepplothother.2)测试:sterfunctionsmunctionsmunctionsMayInterfionsMayInterferfereWithTests,b

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )专业的PHP集成开发工具

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具