Type annotations needed with try block

I'm trying to use a try block, like this:

use anyhow::Result;

fn main() -> Result<(), Box<dyn Error>> {
	match try {
		let n = might_error()?;
	} {
		Ok(_) => { eprintln!("Everything fine"); },
		Err(_) => { eprintln!("Calculation failed"); },
	}
}

fn might_error() -> Result<u32> {
	Ok(0)
}

But I'm getting:

error[E0282]: type annotations needed
  --> src\main.rs:25:24
   |
25 |         let n = might_error()?;
   |                              ^ cannot infer type of error for `?` operator
   |
   = note: `?` implicitly converts the error value into a type implementing `From<anyhow::Error>`

Yes, the question mark operator will always insert an error conversion via the From trait. Since the output error type is not fixed in any way, it is unable to figure out what the error type should be.

Yes, type inference concerns are a major part of why try is not stable.

See https://rust-lang.github.io/rfcs/3058-try-trait-v2.html#possibilities-for-try for some discussion of possible future changes to make this less annoying.

Is there a workaround for now? Like... where do I annotate the type?

This example was somewhat stripped down, in reality it's actually in a Rouille closure which makes it a bit more complex:

    rouille::start_server(format!("{}:{}", ip, port), move |request| {   
	    match try {
		    let n = might_error()?;
		    Response::text("Calculation complete")		    
	    } {
		    Ok(resp) => resp,
		    Err(_) => Response::text("Calculation failed").with_status_code(500),
	    }
    });

You can assign the result of a try block to a variable and add a type annotation to this variable.

1 Like

If your actual code doesn't need the error details, you could try going through Option, which doesn't need annotations because it doesn't involve From (anymore).

Something like

	    match try {
		    let n = might_error().ok()?;
		    Response::text("Calculation complete")		    
	    } {
		    Some(resp) => resp,
		    None => Response::text("Calculation failed").with_status_code(500),
	    }

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.