Analyzer Quirk?

    // ten random binary numbers
    let Rv::U8(vecu8) = ru8.ranv_in(10,0.,1.) else {
       return rerror("type","Pattern extraction failed for random bytes")?; 
    println!("\nBinary numbers: {}",stringv(&vecu8)); 

In this code rerror("type","Pattern extraction failed for random bytes")? evaluates to a custom Error to be returned.

Analyzer complains and says return should be removed as unnecessary, when it is in fact necessary,
otherwise the compiler complains that let..else is not divergent.

This is because there is a ? (question mark postfix operator) coming after rerror(/*…*/):

return rerror("type","Pattern extraction failed for random bytes")?; // <--

This operator is already short-circuiting and return is indeed unnecessary. You should remove the ? if you prefer return. (And it is indeed considered good style in this case).

It's necessary because of let else, since question mark is not guaranteed to return early.

What's the output of cargo check and cargo clippy on this code? Probably there's some lint with a false-positive.

Whatever is generating the complaint may prefer

    return rerror("...", "...").map_err(Into::into)
1 Like

Tried to reproduce this in playground, and, indeed, that's a Clippy false-positive:

fn foo() -> Result<(), ()> {
    let Some(s) = Some("") else {
        return Err(())?;

It probably could be tweaked to suggest the change quinedot mentioned instead. Filed an issue for Clippy.


Ah, you’re right. Even Err(…)? is not considered as an early return. In any case, something like the following would feel more natural than mixing return and ?.

return Err(make_error(/*…*/));

With make_error returning an error type not wrapped into a Result.

Now that you mention it, I realize maybe the original post was lacking details (including a compilable sample that can be run in the playground), and I answered too fast.

I have actually recently subsumed the verbiage Err(...) into my function rerror, as its whole purpose is to make returning custom errors (from many places) as simple as possible. Mostly it works fine and makes for a more compact code. Though I agree that returning an error already wrapped in Result is perhaps somewhat unusual. It is only when trying to use this within let ... else that this problem arises, so I thank Cerber-Ursi for filing it as an issue for Clippy.

Either your reverting to Err(...), or the simpler removal of ? make the problem go away, for now:

return rerror("type","Pattern extraction failed for random bytes");

I have a similar type of problem, should i post it here or i have to start a new thread?

Hard to say. Perhaps post it here and if it's deemed different enough to warrant, the topic can be split.

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.