如何指定闭包参数的生命周期? [英] How can I specify a lifetime for closure arguments?
问题描述
Playpen链接: http://is.gd/EpX6lM
Playpen link: http://is.gd/EpX6lM
我有一个闭包,它需要一个切片,并返回它的子切片。在rust-1.0.0-beta-2上编译以下代码失败:
I have a closure that takes a slice and returns a subslice of it. Compiling the following code on rust-1.0.0-beta-2 fails:
trait OptionalFirst {
fn optional_first<'a>(&self, x: &'a [usize]) -> &'a [usize];
}
impl<F> OptionalFirst for F where F: Fn(&[usize]) -> &[usize] {
fn optional_first<'a>(&self, x: &'a [usize]) -> &'a [usize] {
(*self)(x)
}
}
fn main() {
let bc: Box<OptionalFirst> = Box::new(
|x: &[usize]| -> &[usize] {
if x.len() != 0 {
&x[..1]
}
else {
&x[..0]
}
}) as Box<OptionalFirst>;
let a: [usize; 3] = [1, 2, 3];
let b: &[usize] = bc.optional_first(&a);
println!("{:?}", b);
}
我知道如何在闭包的类型中定义一个生命周期$ c> for<'a> ),但我不知道如何在闭包的实现中指定它。
I know how to define a lifetime in a closure's type (using for <'a>
), but I don't know how to specify it in the closure's implementation.
推荐答案
您的实现 impl< F> OptionalFirst for F其中F:Fn(& [usize]) - > & [usize] 期望有一个绑定生命周期参数,对于约束
F:Fn(& [usize]) - & [usize]
已扩展为完整格式: F:for&'a' Fn(&'a [usize]) - > &'a [usize]
。
Your implementation impl<F> OptionalFirst for F where F: Fn(&[usize]) -> &[usize]
is expecting a bound lifetime parameter, for the constraint F: Fn(&[usize]) -> &[usize]
is, expanded to full form: F: for<'a> Fn(&'a [usize]) -> &'a [usize]
.
也就是说,在调用函数时,它将确定为生命周期(它们是泛型)。
That is, at the time you call the function, it will determine what values to select for the lifetime (they are generics).
但是,闭包不能有任何绑定的生命周期参数;它们是使用具体生命周期参数卡住的。它们缺乏将输出生命周期一般性地连接到输入生命周期的设施:它们是非常设计具体的而不是通用的。我没有深入思考这一点,但它可能可能抵消这一般的生命周期参数;
A closure, however, cannot have any bound lifetime parameters; they are by stuck using concrete lifetime parameters. They lack the facility to wire output lifetimes to input lifetimes generically as you want: they are by very design concrete and not generic. I haven’t thought about this in great depth, but it might be possible to counteract this for generic lifetime parameters; it is not, however, something that is implemented as far as I am aware.
如果你想要这样的东西,尝试使用一个函数,而不是一个闭包。
If you want something like this, try using a function rather than a closure. When you’re not using any of the environment there’s no benefit to using closures beyond the typically lower verbosity.
以下是你最终得到的结果:
Here’s what you end up with:
fn bc(x: &[usize]) -> &[usize] {
if x.len() != 0 {
&x[..1]
} else {
&x[..0]
}
}
这篇关于如何指定闭包参数的生命周期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!