gpt4 book ai didi

rust - Rust,在闭包内创建一个闭包,避免 “closure may outlive the current function”

转载 作者:行者123 更新时间:2023-12-03 11:33:15 24 4
gpt4 key购买 nike

我正在尝试编写一个函数来转换以下形式的数据结构:

input = [("a", [1,2,3]), ("b", [4,5,6])]

进入
output = [(a,1), (c,2) ..... (b,6)] 

我的代码当前是这样的:
    let foo=vec![('a', vec![1,2,3]), ('v', vec![2,3,4])];
let baz: Vec<(char,i32)> = foo.into_iter().map(|a|a.1.into_iter().map( |b|(a.0, b))).flatten().collect();
println!("{:?}",baz);

我收到此错误:
error[E0373]: closure may outlive the current function, but it borrows `a`, which is owned by the current function
--> src/lib.rs:10:76
|
10 | let baz: Vec<(char,i32)> = foo.into_iter().map(|a|a.1.into_iter().map( |b|(a.0, b))).flatten().collect();
| ^^^ - `a` is borrowed here
| |
| may outlive borrowed value `a`
|
note: closure is returned here
--> src/lib.rs:10:55
|
10 | let baz: Vec<(char,i32)> = foo.into_iter().map(|a|a.1.into_iter().map( |b|(a.0, b))).flatten().collect();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
help: to force the closure to take ownership of `a` (and any other referenced variables), use the `move` keyword
|
10 | let baz: Vec<(char,i32)> = foo.into_iter().map(|a|a.1.into_iter().map( move |b|(a.0, b))).flatten().collect();
| ^^^^^^^^

error[E0382]: borrow of moved value: `a`
--> src/lib.rs:10:76
|
10 | let baz: Vec<(char,i32)> = foo.into_iter().map(|a|a.1.into_iter().map( |b|(a.0, b))).flatten().collect();
| --- ^^^ - borrow occurs due to use in closure
| | |
| value moved here value borrowed here after partial move
|
= note: move occurs because `a.1` has type `std::vec::Vec<i32>`, which does not implement the `Copy` trait

我认为这意味着Rust不知道如何复制我的i32s向量,因此认为它必须改为移动vec,但不能这样做。

我该如何解决这个问题?为vec实现Copy方法,还是有一个更简洁的方法来做到这一点?

最佳答案

IntoIterator使用并产生值。由于Vec没有实现Copy,因此当您调用a.1.into_iter()时,它将被移动。您可以像这样克隆它:a.1.clone().into_iter()
另外,您还想使用move关键字来获取闭包中a的所有权。

let baz: Vec<(char, i32)> = foo
.into_iter()
.map(|a| a.1.clone().into_iter().map(move |b| (a.0, b)))
.flatten()
.collect();
println!("{:?}", baz);
// [('a', 1), ('a', 2), ('a', 3), ('v', 2), ('v', 3), ('v', 4)]

关于rust - Rust,在闭包内创建一个闭包,避免 “closure may outlive the current function”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61002805/

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