HashSet Union Difference Intersection
HashSet union, intersection, difference, and symmetric_difference compute set algebra on permission lists; iteration order is random so display sorts.
Code
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
Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.Bitwise Operations CalculatorCompute AND, OR, XOR, NOT, and shifts on 32-bit unsigned operands with binary, hex, and signed decimal views.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.