[英]Conflicting lifetime requirement for iterator returned from function
This may be a duplicate. 这可能是重复的。 I don't know.
我不知道。 I couldn't understand the other answers well enough to know that.
我无法完全理解其他答案。 :)
:)
Rust version: rustc 1.0.0-nightly (b47aebe3f 2015-02-26) (built 2015-02-27) Rust版本:rustc 1.0.0-nightly(b47aebe3f 2015-02-26)(内置2015-02-27)
Basically, I'm passing a bool to this function that's supposed to build an iterator that filters one way for true and another way for false. 基本上,我将一个布尔值传递给此函数,该函数应该构建一个迭代器,该迭代器将一种方式过滤为true,将另一种方式过滤为false。 Then it kind of craps itself because it doesn't know how to keep that boolean value handy, I guess.
然后,它本身就有点麻烦了,因为我猜想它不知道如何方便地保持布尔值。 I don't know.
我不知道。 There are actually multiple lifetime problems here, which is discouraging because this is a really common pattern for me, since I come from a .NET background.
实际上,这里存在多个生命周期问题,这令人沮丧,因为这对我来说是一种非常常见的模式,因为我来自.NET背景。
fn main() {
for n in values(true) {
println!("{}", n);
}
}
fn values(even: bool) -> Box<Iterator<Item=usize>> {
Box::new([3usize, 4, 2, 1].iter()
.map(|n| n * 2)
.filter(|n| if even {
n % 2 == 0
} else {
true
}))
}
Is there a way to make this work? 有没有办法使这项工作?
You have two conflicting issues, so let break down a few representative pieces: 您有两个相互矛盾的问题,因此让我们分解几个代表性的部分:
[3usize, 4, 2, 1].iter()
.map(|n| n * 2)
.filter(|n| n % 2 == 0))
Here, we create an array in the stack frame of the method, then get an iterator to it. 在这里,我们在方法的堆栈框架中创建一个数组,然后对其进行迭代。 Since we aren't allowed to consume the array, the iterator item is
&usize
. 由于不允许使用数组,因此迭代器项为
&usize
。 We then map from the &usize
to a usize
. 然后,我们从
&usize
到usize
。 Then we filter against a &usize
- we aren't allowed to consume the filtered item, otherwise the iterator wouldn't have it to return! 然后,我们针对
&usize
过滤-不允许使用已过滤的项目,否则迭代器将无法返回它!
The problem here is that we are ultimately rooted to the stack frame of the function. 这里的问题是我们最终植根于函数的堆栈框架。 We can't return this iterator, because the array won't exist after the call returns!
我们无法返回此迭代器,因为调用返回后该数组将不存在!
To work around this for now, let's just make it static. 要暂时解决此问题,让我们使其静态化。 Now we can focus on the issue with
even
. 现在我们可以用
even
来关注这个问题。
filter
takes a closure. filter
需要关闭。 Closures capture any variable used that isn't provided as an argument to the closure. 闭包捕获使用的未作为闭包参数提供的任何变量。 By default, these variables are captured by reference.
默认情况下,这些变量是通过引用捕获的。 However,
even
is again a variable located on the stack frame. 但是,
even
还是位于堆栈框架上的变量。 This time however, we can give it to the closure by using the move
keyword. 但是,这次,我们可以使用
move
关键字将其提供给闭包。 Here's everything put together: 这是所有内容的总和:
fn main() {
for n in values(true) {
println!("{}", n);
}
}
static ITEMS: [usize; 4] = [3, 4, 2, 1];
fn values(even: bool) -> Box<Iterator<Item=usize>> {
Box::new(ITEMS.iter()
.map(|n| n * 2)
.filter(move |n| if even {
n % 2 == 0
} else {
true
}))
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.