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?

【Rust】Result と Option の相互変換

Last updated at Posted at 2023-11-30

よく使う型変換の tips です。

Result -> Option

let res: Result<&str, &str> = Ok("hogehoge");

assert_eq!(Some("hogehoge"), res.ok());

ErrNone になります。

Option -> Result

let opt = Some("fugafuga");

assert_eq!(Ok("fugafuga"), opt.ok_or("error!"));

let opt: Option<&str> = None;

assert_eq!(Err("error!"), opt.ok_or("error!"));

ok_or の引数には None のときに Err としてとる値を記述する必要があります。

Option, Result を安全に unwrap

let opt = Some("hogehoge");

assert_eq!("hogehoge", opt.unwrap_or("fugafuga"));

let opt = None;

assert_eq!("fugafuga", opt.unwrap_or("fugafuga"));

let res: Result<&str, &str> = Ok("hogehoge");

assert_eq!("hogehoge", res.unwrap_or("fugafuga"));

let res: Result<&str, &str> = Err("error!");

assert_eq!("fugafuga", res.unwrap_or("fugafuga"));

unwrap_orunwrap 失敗時に使われるデフォルト値を設定して unwrap する関数です。

おわり

or より or_else の方がパフォーマンス的に推奨されますが、or_else は定数の代わりに関数書かないといけないのでちょっと敬遠しがちです。

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?