gpt4 book ai didi

iterator - 当无法复制 T 时,如何将 Option 列表转换为 T 列表?

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

<分区>

我如何获取 Vec<Option<T>> , 其中T无法复制,解开所有的Some值(value)观?

我在 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);
}

Playground

哪个给出了错误

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

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