yohhoyの日記

技術的メモをしていきたい日記

入れ子Optionの平坦化(flatten)

プログラミング言語RustにおいてOption<Option<T>>からOption<T>へ変換する方法。

// ナイーブな実装
fn flatten<T>(x: Option<Option<T>>) -> Option<T>
  match x {
    Some(x) => x,
    None => None,
  }
}

// and_thenコンビネータ
fn flatten<T>(x: Option<Option<T>>) -> Option<T>
{
  x.and_then(|x| x)
}

// ? (Try)オペレータ[Rust 1.22以降]
fn flatten<T>(x: Option<Option<T>>) -> Option<T>
{
  x?
}

let x : Option<Option<i32>> = Some(Some(42));
let y : Option<Option<i32>> = Some(None);
let z : Option<Option<i32>> = None;
assert_eq!(flatten(x), Some(42));
assert_eq!(flatten(y), None);
assert_eq!(flatten(z), None);

関連URL