You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于UUID和日期聚合Rust结构体向量,求和指定字段

Rust结构体分组聚合实现方案

首先修正你定义的结构体语法问题(字段末尾缺逗号,类型需明确引入对应crate的具体类型):

// 需要先引入uuid和chrono依赖
use uuid::Uuid;
use chrono::NaiveDate;

pub struct MyStruct {
    uuid: Uuid,
    date: NaiveDate,
    value1: i32,
    value2: i32,
    my_type: i8,
}

定义聚合结果结构体

先创建一个用于存储聚合后数据的结构体,保留分组键(uuid+date)和求和后的字段:

#[derive(Debug, Clone)]
pub struct AggregatedMyStruct {
    uuid: Uuid,
    date: NaiveDate,
    sum_value1: i32,
    sum_value2: i32,
}

实现分组求和逻辑

使用HashMap以(Uuid, NaiveDate)作为分组键,遍历所有MyStruct实例累加对应字段值,最后转换为结果数组:

use std::collections::HashMap;

fn aggregate_structs(all_structs: Vec<MyStruct>) -> Vec<AggregatedMyStruct> {
    let mut group_map: HashMap<(Uuid, NaiveDate), (i32, i32)> = HashMap::new();

    for item in all_structs {
        let key = (item.uuid, item.date);
        // 若键不存在则初始化为(0,0),否则直接累加
        let (sum1, sum2) = group_map.entry(key).or_insert((0, 0));
        *sum1 += item.value1;
        *sum2 += item.value2;
    }

    // 将HashMap转换为目标结构体数组
    group_map.into_iter()
        .map(|((uuid, date), (sum_val1, sum_val2))| AggregatedMyStruct {
            uuid,
            date,
            sum_value1: sum_val1,
            sum_value2: sum_val2,
        })
        .collect()
}

完整使用示例

fn main() {
    // 构造测试数据
    let test_data = vec![
        MyStruct {
            uuid: Uuid::parse_str("f9168c5e-ceb2-4faa-b6bf-329bf39fa1e4").unwrap(),
            date: NaiveDate::from_ymd_opt(2024, 5, 1).unwrap(),
            value1: 10,
            value2: 20,
            my_type: 1,
        },
        MyStruct {
            uuid: Uuid::parse_str("f9168c5e-ceb2-4faa-b6bf-329bf39fa1e4").unwrap(),
            date: NaiveDate::from_ymd_opt(2024, 5, 1).unwrap(),
            value1: 30,
            value2: 40,
            my_type: 2,
        },
        MyStruct {
            uuid: Uuid::parse_str("a1b2c3d4-e5f6-7890-abcd-1234567890ab").unwrap(),
            date: NaiveDate::from_ymd_opt(2024, 5, 2).unwrap(),
            value1: 50,
            value2: 60,
            my_type: 1,
        },
    ];

    let aggregated_result = aggregate_structs(test_data);
    println!("{:#?}", aggregated_result);
}

所需依赖(Cargo.toml)

[dependencies]
uuid = { version = "1.0", features = ["v4", "parse"] }
chrono = "0.4"

内容的提问来源于stack exchange,提问作者Antonin GAVREL

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 07:22:48