This test code's let else doesn't compile and I can't figure out why

% rustc --version
rustc 1.79.0 (129f3b996 2024-06-10)

Github link
The refutable let else pattern with diverging else clause, doesn't compile with cargo build --tests with following error:

error: expected `;`
  --> src/resp/simple_string.rs:30:56
   |
30 |         let Resp::SimpleString(simple_string) = result else {
   |                                                        ^^^^

Sorry for not providing minimum reproducible example - I can't even figure out minimum reproducible example. I tried this simplified version of code but it compiles:

(Simplified definition of Resp, SimpleString, BulkString and its impls)
#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_parse_body() {
        let result: Resp = Resp::parse().await.unwrap();

        let Resp::SimpleString(simple_string) = result else {
            panic!();
        };

        assert_eq!(simple_string, SimpleString("OK".to_string()));
    }
}

The weird thing is, removing #[tokio::test] makes it successfully compile, so I tried cargo expanding test attribute but the expanded code does compile without error.
I'm at a loss.

Procedural macros use their own parser like syn, and not Rust's built in parser. It's possible that syn or tokio's implementation doesn't understand this syntax.

3 Likes

EDIT: I am probably wrong. I forgot "let ... else" was a thing.

Maybe you meant to use "if let"

I get your code to compile with this.


        if let Resp::SimpleString(simple_string) = result {
            assert_eq!(simple_string, SimpleString("OK".to_string()));
        } else {
            panic!("expected SimpleString, got {:?}", result);
        };

Especially because this repo is using a version of tokio that still depends on syn 1.0. Running cargo update will upgrade tokio and syn to more modern versions.

3 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.