本文簡要介紹rust語言中 std::option::Option.filter
的用法。
用法
pub fn filter<P>(self, predicate: P) -> Option<T> where P: FnOnce(&T) -> bool,
如果選項是 None
則返回 None
,否則使用包裝的值調用 predicate
並返回:
此函數的工作方式類似於 Iterator::filter()
。您可以想象Option<T>
是一個或零個元素的迭代器。 filter()
讓您決定保留哪些元素。
例子
fn is_even(n: &i32) -> bool {
n % 2 == 0
}
assert_eq!(None.filter(is_even), None);
assert_eq!(Some(3).filter(is_even), None);
assert_eq!(Some(4).filter(is_even), Some(4));
相關用法
- Rust Option.flatten用法及代碼示例
- Rust Option.unwrap_or_default用法及代碼示例
- Rust Option.as_deref_mut用法及代碼示例
- Rust Option.get_or_insert_with用法及代碼示例
- Rust Option.iter_mut用法及代碼示例
- Rust Option.or_else用法及代碼示例
- Rust Option.unwrap_unchecked用法及代碼示例
- Rust Option.get_or_insert用法及代碼示例
- Rust Option.expect用法及代碼示例
- Rust Option.get_or_insert_default用法及代碼示例
- Rust Option.insert用法及代碼示例
- Rust Option.map_or用法及代碼示例
- Rust Option.as_mut用法及代碼示例
- Rust Option.map用法及代碼示例
- Rust Option.and_then用法及代碼示例
- Rust Option.unwrap_or用法及代碼示例
- Rust Option.transpose用法及代碼示例
- Rust Option.iter用法及代碼示例
- Rust Option.as_deref用法及代碼示例
- Rust Option.contains用法及代碼示例
- Rust Option.as_ref用法及代碼示例
- Rust Option.replace用法及代碼示例
- Rust Option.unwrap用法及代碼示例
- Rust Option.zip_with用法及代碼示例
- Rust Option.zip用法及代碼示例
注:本文由純淨天空篩選整理自rust-lang.org大神的英文原創作品 std::option::Option.filter。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。