Is there a shorthand form of the match in Rust?

不想你离开。 提交于 2021-02-10 15:16:54

问题


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?

来源:https://stackoverflow.com/questions/50523267/is-there-a-shorthand-form-of-the-match-in-rust

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!