1

Many function calls in Rust return the type std::result::Result which is an enum. There are advantages of having such a return type, but writing a matcher looks to be tedious for a small task.

For example, I was trying to find the time a certain portion of my code takes. I tried SystemTime::now() coupled with duration():

let now = SystemTime::now();

let result = cvar
    .wait_timeout(started, Duration::from_millis(20000))
    .unwrap();
started = result.0;
if *started == false {
    *started = true;
}
println!("Thread 1 :: Exiting...after {:?}s ", now.elapsed().unwrap());

This gives me an output in the shape of

Thread 1 :: Exiting...after Duration { secs: 6, nanos: 999860814 }s

I am aware that I can get the desired result using a match in a similar manner to this as in the docs:

match now.elapsed() {
    Ok(elapsed) => {
        println!("{}", elapsed.as_secs());
    }
    Err(e) => {
        println!("Error: {:?}", e);
    }
}

This would be a few extra lines which do not really contribute to the application logic.

Is there no shorthand for carrying out such a match operation?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Rajeev Ranjan
  • 3,588
  • 6
  • 28
  • 52
  • 1
    Possible duplicate of [Unwrap or continue in a loop](https://stackoverflow.com/questions/49785136/unwrap-or-continue-in-a-loop) – Stargateur May 25 '18 at 07:13
  • One way could be `now.elapsed().and_then(|x| { println!("Thread 1 :: Exiting...after {:?}s ", x); Ok(x) });` – Stargateur May 25 '18 at 07:13
  • 7
    Are you searching for something like https://blog.rust-lang.org/2016/11/10/Rust-1.13.html#the--operator ? – hellow May 25 '18 at 07:56
  • Oh that's a nice construct @hellow .But perhaps it isn't working in my case complaining - `cannot use the `?` operator in a function that returns '()'`. – Rajeev Ranjan May 25 '18 at 08:26
  • 1
    you have to return a result ;) see the example in the blog update. also see https://stackoverflow.com/questions/42917566/what-is-this-question-mark-operator-about and https://stackoverflow.com/questions/40545332/is-the-question-mark-operator-equivalent-to-the-try-macro – hellow May 25 '18 at 08:36
  • ok I see. Ultimately the error has to be propagated anyhow which demands the return type to be `Result` anyhow. – Rajeev Ranjan May 25 '18 at 08:47

0 Answers0