如何处理一个 Vec<Option<T>>
,其中 T
不能被复制,并且展开所有的 Some
值?
在 map
步骤中遇到了错误。我很乐意移动原始列表的所有权并“丢弃” None
。
#[derive(Debug)]
struct Uncopyable {
val: u64,
}
fn main() {
let num_opts: Vec<Option<Uncopyable>> = vec![
Some(Uncopyable { val: 1 }),
Some(Uncopyable { val: 2 }),
None,
Some(Uncopyable { val: 4 }),
];
let nums: Vec<Uncopyable> = num_opts
.iter()
.filter(|x| x.is_some())
.map(|&x| x.unwrap())
.collect();
println!("nums: {:?}", nums);
}
这会引发错误
error[E0507]: cannot move out of borrowed content
--> src/main.rs:17:15
|
17 | .map(|&x| x.unwrap())
| ^-
| ||
| |hint: to prevent move, use `ref x` or `ref mut x`
| cannot move out of borrowed content
filter_map
来使其更短。 - llogiq.cloned()
的解决方案。感谢巧妙的filter_map
。 - Matthieu M.into_iter()
。 - llogiqidentity
代替|x| x
。文档中甚至有一个覆盖这个确切用例的示例。 - nirvana-msuflat_map
是什么意思? - ecoe