HashSet Union Difference Intersection

HashSet union, intersection, difference, and symmetric_difference compute set algebra on permission lists; iteration order is random so display sorts.

RustSecurity Boundaries

Code

rustsnippet
33 lines
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));
}

Inside the snippet

HashSet Union Difference Intersection keeps everything in the functions sorted and main.

Putting it to use

The main signature reads fn sorted(set: &HashSet<&str>) -> Vec<&str>

The run emits 6 labeled sections — union:, intersection:, granted:, symmetric:, deny subset of allow:, read-only subset of allow: — one per step.

The sequence sorted lives in main; running the file triggers it.

Core lines

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();

Interactive Tools for This Topic

FAQ

What does HashSet Union Difference Intersection print when run?
Invoke the file as-is — the `union:`, `intersection:`, `granted:` prefixes identify which step printed each line.