Exception Handling
📚 Reference
- https://doc.rust-lang.org/std/result/index.html
- https://doc.rust-lang.org/std/option/index.html
📝 Report
はじめに
RustのResult, Optionについて整理しておきたい。 どちらも列挙型です。これらの型を用いることで、例外処理を扱います。 Rustのバージョンは1.75.0です。
Result型
#![allow(unused)] fn main() { enum Result<T, E> { Ok(T), Err(E), } }
Methods
(ほぼOptionと同じだ)
Option型
#![allow(unused)] fn main() { pub enum Option<T> { None, Some(T), } }
Option<T>型はNoneまたはSome(T)を指します。
Noneは他言語でいうnullです、値がないことを示します。
Some(T)はT型の値を持つSome型を示します。
Methods
使い分けが難しいと感じるものを整理します。
Some(T)を取り出す
Noneが返る場合の挙動が下記のように異なります。
- exprect
- 指定した文言でpanicさせる
- unwrap
- コンパイラ?生成文言でpanicさせる
- unwrap_or
- 指定した値を返す
- unwrap_or_default
- unwrap_or_else
- 指定したstd::ops::FnOnceの戻り値を返す
型を変換する
Result型へ
- ok_or
Some(T)をOk(T)へ、NoneをErr(err)へ。errは指定した値。
- ok_or_else
Some(T)をOk(T)へ、NoneをErr(err)へ。errは指定したstd::ops::FnOnce。
- transpose
Option<Result<T>>をResult<Option<T>>へ
Someを変える
型を変える
Some(T)の場合、指定したstd::ops::FnOnceの戻り値を返す
- map_or
Noneの場合、指定した値を返す
- map_or_else
Noneの場合、指定したstd::ops::FnOnceの戻り値を返す
その他
下記は省略しました、公式ドキュメントを参照しましょう。
- Querying the variant
- Adapters for working with references 参照型との調整
- Boolean operators
- Comparison operators
- Iterating over Option
- Collecting into Option
- Modifying an Option in-place
共通
? operator
?オペレーターを使用した値は
Noneが返る場合は近しいブロックをNoneで抜けます。
それ以外はSome(T)をunwrap()した値になります。