0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Rustのok_orの便利の使い方

Posted at

There are many methods can be used to check if an Option has value. For examples:

Use is_some() or is_none():

    if x.is_some() {
        println!("test_with_if i is {:?}", x.unwrap());
    }

Use match:

    match x {
        None => {}
        Some(i) => {
            println!("test_with_match i is {:?}", i);
        }
    }

Use if let:

    if let Some(i) = x {
        println!("test_with_if_let i is {:?}", i);
    };

Or if ok_or to convert it to Result type and then process as Result:


    let _ = x.ok_or(NotFoundError).and_then(|i| {
        println!("test_with_ok_or i is {:?}", i);
        Ok(i)
    });

すべてのコードは ここ

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?