HashSet Get Returns Canonical Entry

Look up equivalent keys with HashSet::get to retrieve the canonical stored form, so repeated normalization never duplicates entries.

RustData Integrity

Code

rustsnippet
21 lines
use std::collections::HashSet;

fn normalize(tag: &str) -> String {
    tag.trim().to_lowercase()
}

fn main() {
    let mut tags: HashSet<String> = HashSet::new();
    tags.insert(normalize("  Rust  "));

    // get 用等价键查找,返回集合里实际存储的 canonical entry
    if let Some(canonical) = tags.get("rust") {
        println!("canonical: {canonical:?}");
    }

    // 插入等价值不会新增条目:集合里始终只有规范形式
    let inserted_new = tags.insert(normalize("RUST"));
    println!("inserted new: {inserted_new}");
    println!("size: {}", tags.len());
    println!("contains RUST: {}", tags.contains("RUST"));
}

How this snippet works

Structurally, expect the functions normalize and main and nothing else.

Caveats

  • Nothing external is pulled in — the language’s built-in APIs carry everything.

Applying it

Entry signature: fn normalize(tag: &str) -> String

The run emits 4 labeled sections — canonical:, inserted new:, size:, contains RUST: — one per step.

There are 1 call inside main — normalize — executed top to bottom.

Statements that matter

if let Some(canonical) = tags.get("rust") {
    println!("canonical: {canonical:?}");
}
fn normalize(tag: &str) -> String {
    tag.trim().to_lowercase()
}

Interactive Tools for This Topic

FAQ

What does HashSet Get Returns Canonical Entry print when run?
The script runs standalone; its 4 labeled outputs include `canonical:`, `inserted new:`, `size:`.