4

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?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
atomvinter
  • 87
  • 5
  • Relevant question: https://stackoverflow.com/questions/28225958/why-is-this-match-pattern-unreachable-when-using-non-literal-patterns – Svetlin Zarev Aug 26 '21 at 09:49
  • 1
    `match` doesn't use any equality operator for any type, it uses structural equality. You can't change that. – mcarton Aug 26 '21 at 10:11

1 Answers1

2

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.

Netwave
  • 40,134
  • 6
  • 50
  • 93
  • 1
    I fail to see how "write your own type wrapper" would help, unless the type wrapper would essentially require a `new` function that calls `to_lowercase`. And the OP contains the example with `to_lowercase`, so I fail to see how your `to_ascii_lowercase` is useful. – mcarton Aug 26 '21 at 10:13
  • @mcarton, would you mind expand why would `to_ascii_lowercase` do not work? You are right about the wrapper type though. He would have to transform the underliying item anyway. – Netwave Aug 26 '21 at 11:14
  • `to_ascii_lowercase` would work, but it's barely an improvement when the OP mentions `to_lowercase` already. – mcarton Aug 26 '21 at 12:02