0

I'm trying to understand the ? keyword of Rust.

For that, I've written the following sample

use std::env;
fn main() {
    let first = env::args().nth(1)?;
    let n: i32 = first.parse()?;
    println!("Hello, world!");
}

I'm quite sure the env::args.nth(1) returns an Option, which implements the Try trait. When I try to compile, I get the following error message

error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `std::ops::Try`)
--> src\main.rs:3:17
|
3 |     let first = env::args().nth(1)?;
|                 ^^^^^^^^^^^^^^^^^^^ cannot use the `?` operator in a function that returns `()`
|
= help: the trait `std::ops::Try` is not implemented for `()`
= note: required by `std::ops::Try::from_error`

What am I doing wrong?

hellow
  • 12,430
  • 7
  • 56
  • 79
Riduidel
  • 22,052
  • 14
  • 85
  • 185
  • 6
    `?` handles the error by immediately returning from the _enclosing function_ and propagating the error upwards. This can't work if the enclosing function doesn't itself return a `Result`. – Peter Hall Sep 14 '18 at 09:59
  • In this case your function must not return a `Result`, but instead an `Option` (or you provide a `Try` impl, so that you can convert an `Option` to a desired `Result` – hellow Sep 14 '18 at 10:45

0 Answers0