gpt4 book ai didi

foreach - 为什么 `Option` 支持 `IntoIterator` ?

转载 作者:行者123 更新时间:2023-11-29 07:42:43 24 4
gpt4 key购买 nike

我试图遍历字符串向量的一个子部分,即 Vec<String> 的子切片.在每次迭代中,我想将字符串作为切片传递给函数。

我没注意到 Vec::get返回 Option ,并认为我可以直接迭代返回值:

fn take_str(s: &str) {
println!("{}", s);
}

fn main() {
let str_vec: Vec<String> = ["one", "two", "three", "uno", "dos", "tres"]
.iter()
.map(|&s| s.into())
.collect();
for s in str_vec.get(0..3) {
take_str(&s);
}
}
error[E0308]: mismatched types
--> src/main.rs:11:18
|
11 | take_str(&s); // Type mismatch: found type `&&[std::string::String]`
| ^^ expected `str`, found `&[String]`
|
= note: expected reference `&str`
found reference `&&[String]`

我期待 s成为String , 但它实际上是 &[String] .这是因为我的 for循环遍历 OptionVec::get() 返回.

我还写了下面的代码,它演示了 for循环实际上是在展开一个 Option :

let foo = Option::Some(["foo".to_string()]);
for f in foo {
take_str(&f); // Same error as above, showing `f` is of type `&[String]`
}

这非常令人困惑;我从没想过(直到我写了这段代码并弄清楚它实际上在做什么)Option可以通过对其进行迭代 来展开。为什么支持?迭代 Option 有什么用例? ?

最佳答案

What use case is there for iterating over an Option?

一句话,我最喜欢的理由是flatten :

fn main() {
let results = [Some(1), None, Some(3), None];
let sum: i32 = results.into_iter().flatten().sum();
println!("{}", sum)
}

在 Rust 1.29 之前,您可以使用 flat_map :

fn main() {
let results = vec![Some(1), None, Some(3), None];
let sum: i32 = results.into_iter().flat_map(|x| x).sum();
println!("{}", sum)
}

Option 可以被认为是一个可以容纳零个或一个元素的容器。将其与 Vec 进行比较,它可以包含零个或多个元素。在很多方面,Option 就像 Vec 一样是一个容器!

实现 IntoIterator 允许 Option 参与更大份额的 API。

请注意,出于类似原因,IntoIterator Result 实现。

This is incredibly confusing

是的,这就是为什么 Clippy has a lint for it :

warning: for loop over `str_vec.get(0..3)`, which is an `Option`. This is more readably written as an `if let` statement
--> src/main.rs:10:14
|
10 | for s in str_vec.get(0..3) {
| ^^^^^^^^^^^^^^^^^
|
= note: `#[warn(clippy::for_loops_over_fallibles)]` on by default
= help: consider replacing `for s in str_vec.get(0..3)` with `if let Some(s) = str_vec.get(0..3)`
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#for_loops_over_fallibles

这表明 Option 在某些方面不像程序员的容器。

关于foreach - 为什么 `Option` 支持 `IntoIterator` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43285372/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com