FAQ - Help and questions

Why does Rust say the "? operator can only be used in a function that returns Result or Option"?

#errors#error-handling#resultpublished 2 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail
Last post

Short answer

The ? operator returns an error from the current function early, so that function must be able to return one. Inside main, or any function that returns (), change the return type to Result with a suitable error type and end with Ok(()). Otherwise handle the error with match or unwrap.

Checked with rustc 1.93.0, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

value? means "if this is an Err, return it from here; if it is Ok, give me the inside". A function whose return type is () has nowhere to return an error to, so the compiler refuses (error E0277). The usual place to meet this is main.

src/main.rsrust
fn main() {
    let n: i32 = "42".parse()?;
    println!("{n}");
}
text
error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`)
 --> src/main.rs:2:30
  |
1 | fn main() {
  | --------- this function should return `Result` or `Option` to accept `?`
2 |     let n: i32 = "42".parse()?;
  |                              ^ cannot use the `?` operator in a function that returns `()`
  |
help: consider adding return type
  |
1 ~ fn main() -> Result<(), Box<dyn std::error::Error>> {
2 |     let n: i32 = "42".parse()?;
3 |     println!("{n}");
4 +     Ok(())
  |

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0277`.

The answers below are the two valid ways to fix it.

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    2 answers from the Ruststudio team: different approaches, each with its own trade-offs

    Sort: Oldest Newest
    #2

    Approach 1: make the function return a Result#

    For main, the return type Result<(), E> is allowed. If an error comes back, the program prints it and exits with a failure code. Use the specific error type, or Box<dyn std::error::Error> to accept any error.

    src/main.rsrust
    fn main() -> Result<(), std::num::ParseIntError> {
        let n: i32 = "42".parse()?;
        println!("{n}");
        Ok(())
    }
    text
    42

    Best when: the error should end the program or be passed up to a caller.

      QuoteReply
      Share
      Hacker NewsRedditLinkedInE-mail
      #3

      Approach 2: handle the error where it happens#

      Use match, if let, or unwrap_or when this function is the right place to decide what happens.

      rust
      fn main() {
          let n: i32 = "42".parse().unwrap_or(0);
          println!("{n}");
      }

      Best when: a default or a message to the user is the right reaction, and the function should keep returning ().

      Common mistakes#

      • Using ? on an Option in a function that returns Result (or the reverse). Convert with .ok_or(error)? (Option to Result) or .ok()? (Result to Option).
      • Returning Result<(), String> and then finding that ? on a ParseIntError fails: the error type must be convertible. Box<dyn Error> accepts all standard errors.
        QuoteReply
        Share
        Hacker NewsRedditLinkedInE-mail