← 中文资源

简体中文版本

HashSet 的并集交集与差集

HashSet 的 union/intersection/difference/symmetric_difference 对权限集合做代数运算:迭代顺序随机,展示前先排序输出才稳定,is_subset 做包含判断。

阅读英文原文

实现说明

全部逻辑都在函数 sorted、main中。

使用要点

  • 演示输出是带标签的(union:、intersection:、granted:),每个操作都会留下自己的一行标注。
  • 运行整个文件:main 会依次驱动 sorted。

常见问题

运行「HashSet 的并集交集与差集」会打印什么?

整个文件跑完,输出行以 union:、intersection:、granted: 这类前缀开头。

签名一览:fn sorted(set: &HashSet<&str>) -> Vec<&str>

核心语句

let mut items: Vec<&str> = set.iter().copied().collect();
let either: HashSet<_> = allow.symmetric_difference(&deny).copied().collect();
let granted: HashSet<_> = allow.difference(&deny).copied().collect();

代码示例

use std::collections::HashSet;

// HashSet 迭代顺序随机:展示前先排序,输出才可复现
fn sorted(set: &HashSet<&str>) -> Vec<&str> {
    let mut items: Vec<&str> = set.iter().copied().collect();
    items.sort_unstable();
    items
}

fn main() {
    let allow: HashSet<&str> = ["read", "write", "delete"].into();
    let deny: HashSet<&str> = ["write", "exec"].into();

    // 并集:任一集合出现的权限都保留
    let union: HashSet<_> = allow.union(&deny).copied().collect();
    println!("union: {:?}", sorted(&union));

    // 交集:同时出现在 allow 与 deny 的权限
    let both: HashSet<_> = allow.intersection(&deny).copied().collect();
    println!("intersection: {:?}", sorted(&both));

    // 差集:允许但未被拒绝的权限(allowlist 减去 denylist)
    let granted: HashSet<_> = allow.difference(&deny).copied().collect();
    println!("granted: {:?}", sorted(&granted));

    // 对称差:只属于其中一边的权限
    let either: HashSet<_> = allow.symmetric_difference(&deny).copied().collect();
    println!("symmetric: {:?}", sorted(&either));

    let ro: HashSet<&str> = ["read"].into();
    println!("deny subset of allow: {}", deny.is_subset(&allow));
    println!("read-only subset of allow: {}", ro.is_subset(&allow));
}