Match on i32 - function call in pattern

With

let c: i32 =ncurses::getch();

we can do

if c=='q' as i32  {
}

but not

match c {
    'q' as i32 => (),
    _
}

instead we can do

match c {
    113  => (),
    _
}

Is there another way of handling this in match statement?
Function calls are not allowed in patterns...

Constants are allowed as patterns.

While eventually, once we get that feature, something like const { 'q' as i32 } should work, you can define a constant like

const LOWER_Q_CODE: i32 = 'q' as i32;

and use it as a pattern. For this, it's useful that items such as const are also allowed to be defined locally, e. g. within a function, so you can keep it close to where it's used and the visibility limited.

Rust Playground

1 Like

Maybe the pattern gets a little longer but you can do:

match c {
    _ if c=='q' as i32 => (),
    _
}
2 Likes

It's a little more verbose because you need two conversions which are both fallible, but you could try to convert the input into a char for the match

match u32::try_from(c).ok().and_then(char::from_u32) {
    Some('c') => {}
    _ => {}
}
1 Like

Unicode Scalar Values are always small enough that it would be fine to write this as

match char::from_u32(c as u32) {

but

based on getch(3ncurses) — ncurses-doc — Debian bullseye — Debian Manpages, that's not actually returning unicode in the first place, so going via char at all is probably wrong -- KEY_RESIZE is not a unicode character.

Since it mentions

The *get* functions are described in the XSI Curses standard, Issue 4. They read single-byte characters only.

then maybe you'd like

    match c.try_into() {
        Ok(b'q') => …,
        _ => …,
    }

Or I guess you could try a different version of ncurses, and use getch in ncursesw - Rust which seems to be able to give back chars.

6 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.