atomvinter
atomvinter

Reputation: 87

Is it possible to pattern match with a custom equality operator?

I'm just learning Rust, and I was wondering if there is a possibility of taking this code:

match letter.to_lowercase().as_str() {
    "a" => 5,
    "n" => 13,
    // And so on...
    _   => 0,
}

and using String::eq_ignore_ascii_case as the equality operator instead, like in the pseudocode below:

match letter with letter.eq_ignore_ascii_case as operator {
    "a" => 5,
    "n" => 13,
    // And so on...
    _   => 0,
}

Can this be done? If so, how?

Upvotes: 4

Views: 615

Answers (1)

Netwave
Netwave

Reputation: 42678

Short answer, no, unless you write your own type wrapper that actually normalize your input into something you need.

What you can do is to match to_ascii_lowercase:

match letter.to_ascii_lowercase().as_str() {
        "a" => 5,
        "n" => 13,
        // And so on...
        _   => 0,
    }

From the eq_ignore_ascii_case:

Checks that two strings are an ASCII case-insensitive match. Same as to_ascii_lowercase(a) == to_ascii_lowercase(b), but without allocating and copying temporaries.

Upvotes: 2

Related Questions