英文:
What is the idiomatic way to convert a Some into a None given a predicate in Rust?
问题
Here is the translated code:
我想要能够在某些特定条件成立时将 `Some` 转换为 `None`。
例如,如果我有 `Some(false)`,它应该被转换为 `None`,而 `Some(true)` 应该保持为 `Some(true)`。
我找到了一些方法来做到这一点。
```rust
let value1: Option<bool> = Some(false);
let value2: Option<bool> = Some(true);
let result1 = value1.and_then(|inner| if inner == false { None } else { Some(inner) });
let result2 = value2.and_then(|inner| if inner == false { None } else { Some(inner) });
println!("{:?}", result1); // 打印 "None"
println!("{:?}", result2); // 打印 "Some(true)"
或者甚至可以这样做
let value1: Option<bool> = Some(false);
let value2: Option<bool> = Some(true);
let result1 = if let Some(false) = value1 { None } else { value1 };
let result2 = if let Some(false) = value2 { None } else { value2 };
println!("{:?}", result1); // 打印 "None"
println!("{:?}", result2); // 打印 "Some(true)"
我查看了文档,但找不到更简洁的方法来执行此操作。
类似于以下代码:
let value = Some(v).to_none_if(predicate)
其中,如果 predicate 为 true,则 value 将为 None
如果 predicate 为 false,则 value 保持为 Some(v)
在 Rust 中,执行这种类型的转换的最惯用方式是什么?
<details>
<summary>英文:</summary>
I want to be able to convert a `Some` to a `None`, if some certain condition holds true for the value within the Some.
For example if I have `Some(false)` it should be turned into a `None`, while `Some(true)` should remain as `Some(true)`
I found some way to do this.
let value1: Option<bool> = Some(false);
let value2: Option<bool> = Some(true);
let result1 = value1.and_then(|inner| if inner == false { None } else { Some(inner) });
let result2 = value2.and_then(|inner| if inner == false { None } else { Some(inner) });
println!("{:?}", result1); // Prints "None"
println!("{:?}", result2); // Prints "Some(true)"
or even this
let value1: Option<bool> = Some(false);
let value2: Option<bool> = Some(true);
let result1 = if let Some(false) = value1 { None } else { value1 };
let result2 = if let Some(false) = value2 { None } else { value2 };
println!("{:?}", result1); // Prints "None"
println!("{:?}", result2); // Prints "Some(true)"
Looked around the docs' and I could not find a method that does this in a more succinct way.
Something like
let value = Some(v).to_none_if(predicate)
where value will be None, if predicate is true
or value will remain Some(v) if predicate is false
What will be the most idiomatic way in Rust to do this type of transformation?
</details>
# 答案1
**得分**: 5
你要找的是[`filter()`](https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.filter),尽管它的作用与你所要求的相反:如果断言返回**`false`**,它会转换为 `None`。因此,你需要对表达式取反:
```rust
let v = option.filter(|&v| !(v == false));
或者只需:
let v = option.filter(|&v| v);
英文:
What you're looking for is filter()
, although it does the opposite of what you're asking: it converts to None
if the predicate returns false
. So you need to negate the expression:
let v = option.filter(|&v| !(v == false));
Or just:
let v = option.filter(|&v| v);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论