xrl*_*xrl 6 iterator optional rust
如何获取a Vec<Option<T>>,T无法复制的位置以及展开所有Some值?
我在这map一步中遇到了错误.我很高兴移动原始列表的所有权并"扔掉" Nones.
#[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);
}
Run Code Online (Sandbox Code Playgroud)
这给出了错误
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
Run Code Online (Sandbox Code Playgroud)
在Rust中,当您需要值时,通常需要移动元素或克隆它们.
由于移动更为通用,因此只需要进行两项更改:
let nums: Vec<Uncopyable> = num_opts
.into_iter()
// ^~~~~~~~~~~~-------------- Consume vector, and iterate by value
.filter(|x| x.is_some())
.map(|x| x.unwrap())
// ^~~------------------ Take by value
.collect();
Run Code Online (Sandbox Code Playgroud)
正如llogiq指出的那样,filter_map已经专门过滤掉None了:
let nums: Vec<Uncopyable> = num_opts
.into_iter()
// ^~~~~~~~~~~~-------- Consume vector, and iterate by value
.filter_map(|x| x)
// ^~~----- Take by value
.collect();
Run Code Online (Sandbox Code Playgroud)
然后它工作(消费num_opts).