gpt4 book ai didi

rust - 当编译器建议使用 move 关键字时,我应该怎么做才能使迭代器中的生命周期起作用?

转载 作者:行者123 更新时间:2023-11-29 08:35:13 26 4
gpt4 key购买 nike

我有一段代码无法编译:

struct A {
x: [u32; 10],
}

impl A {
fn iter<'a>(&'a self) -> impl Iterator<Item = u32> + 'a {
(0..10).map(|i| self.x[i])
}
}

fn main() {}

( playground )

编译器说:

error[E0373]: closure may outlive the current function, but it borrows `self`, which is owned by the current function
--> src/main.rs:7:21
|
7 | (0..10).map(|i| self.x[i])
| ^^^ ---- `self` is borrowed here
| |
| may outlive borrowed value `self`
help: to force the closure to take ownership of `self` (and any other referenced variables), use the `move` keyword
|
7 | (0..10).map(move |i| self.x[i])
| ^^^^^^^^

我应该怎么做才能使这项工作正常进行?我稍后需要 self,所以我不能按照编译器的建议移动它。

编辑:我相信move 会在以后使用self 时产生问题。例如看代码:

struct A {
x: [u32; 3],
}

impl A {
fn iter<'a>(&'a self) -> impl Iterator<Item=u32> + 'a {
(0..3).filter(move |&i| self.x[i] != 0).map(move |i| self.x[i])
}
}

fn main() {
let a = A { x : [0, 1, 2]};
for el in a.iter() {
println!("{}", el);
}
}

( playground )

这里 &'a self 被移动了两次,所以实际上,两个闭包都获得了 &'a self 的所有权。代码实际上编译了,但我没想到它一旦移动,一个变量就不能再使用了。这本书(relevant section)也举了一个例子来佐证我的理解:

fn main() {
let x = vec![1, 2, 3];
let equal_to_x = move |z| z == x;
println!("can't use x here: {:?}", x);
let y = vec![1, 2, 3];
assert!(equal_to_x(y));
}

此代码无法编译。为什么我的迭代器代码适用于 move

最佳答案

看起来编译器已经告诉你该做什么了:

help: to force the closure to take ownership of `self` (and any other referenced variables), use the `move` keyword
|
7 | (0..10).map(move |i| self.x[i])
| ^^^^^^^^

move 关键字将任何捕获的变量的所有权赋予闭包。

在这里,您通过移动捕获了 self 引用,而不是对象本身。您不能通过调用 iter 方法来使用该对象,因为它不通过移动接受您的对象,而是通过引用接受您的对象。你可以still use your object after calling iter()在一个实例上。

关于rust - 当编译器建议使用 move 关键字时,我应该怎么做才能使迭代器中的生命周期起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52956623/

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