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

Rust如何原地更新原始HashSet存储两集合交集运算结果

问题根因

你写的a = a.intersection(&b).collect::<HashSet<_>>()无法运行的核心原因是类型不匹配:
HashSet::intersection返回的迭代器产出的元素是对集合内元素的共享引用(即&T),在你的示例中集合元素类型是&str,因此迭代器产出的是&&str类型,collect生成的新集合类型为HashSet<&&str>,和原变量a的类型HashSet<&str>不匹配,无法直接赋值。

最优实现:原地求交集(不新建完整集合)

直接使用HashSet内置的retain方法即可,这是真正意义上的原地更新:该方法会直接在原集合上删除不符合条件的元素,不需要额外分配新集合的整块内存,性能最优。

use std::collections::HashSet;
fn main() {
    let mut a = HashSet::from(["first", "second", "third"]);
    let b = HashSet::from(["first", "third", "fifth", "ninth"]);
    
    // 仅保留同时存在于集合b中的元素,等价于原地求交集
    a.retain(|item| b.contains(item));
    
    println!("{:?}", a); // 输出 {"first", "third"}
}
基于intersection的修正写法(非原地)

如果你一定要用intersection方法实现,只需要在迭代器链上加copied()解引用,把&&str转为&str匹配类型即可,但这种方式本质还是会创建全新的HashSet实例,再把变量a绑定到新集合上,不属于真正的原地更新,性能弱于retain方案:

use std::collections::HashSet;
fn main() {
    let mut a = HashSet::from(["first", "second", "third"]);
    let b = HashSet::from(["first", "third", "fifth", "ninth"]);
    
    a = a.intersection(&b).copied().collect();
    
    println!("{:?}", a); // 输出 {"first", "third"}
}
方案对比
  • retain方案:真正原地修改原集合内存,无额外的整集合分配开销,是该场景的首选写法。
  • intersection+collect方案:本质生成新集合后替换变量绑定,原集合内存会被回收,存在额外的内存分配开销,仅适合需要保留交集前原集合数据的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 19:15:34