?
によるOption
のアンパック
Option
をアンパックするにはmatch
文を使うこともできますが、?
を使う方が簡単になることが多いでしょう。Option
のx
があるとすると、x?
を評価した値は、x
がSome
の場合はx
に格納された値となり、そうでなければ実行中の関数を終了させ、None
を返します。
fn next_birthday(current_age: Option<u8>) -> Option<String> {
// If `current_age` is `None`, this returns `None`.
// If `current_age` is `Some`, the inner `u8` value + 1
// gets assigned to `next_age`
let next_age: u8 = current_age? + 1;
Some(format!("Next year I will be {}", next_age))
}
多くの?
を共に使うことで、リーダブルなコードを書くことができます。