简体   繁体   English

如何在返回类型中使用带有匿名闭包的更高等级特征边界

[英]How to use Higher Rank Trait Bounds with anonymous closure in return type

Is it possible to return FnMut closure that takes reference and return reference with same lifetime as it takes?是否可以返回带有引用的FnMut闭包并返回具有相同生命周期的引用?

fn fun(buf: &mut [f32], mut idx: usize) -> impl FnMut(&[i16]) -> &[i16] {
    |input| {
        buf[idx] = input[0] as f32;
        idx += 1;
        &input[1..]
    }
}

I've tried things like impl for<'a> FnMut(&'a [i16]) -> &'a [i16]) and it gives我已经尝试过诸如impl for<'a> FnMut(&'a [i16]) -> &'a [i16])之类的东西,它给出了

error[E0482]: lifetime of return value does not outlive the function call
 --> src/main.rs:1:44
  |
1 | fn fun(buf: &mut [f32], mut idx: usize) -> impl for<'a> FnMut(&'a [i16]) -> &'a [i16] {
  |                                            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
note: the return value is only valid for the anonymous lifetime defined on the function body at 1:13
 --> src/main.rs:1:13
  |
1 | fn fun(buf: &mut [f32], mut idx: usize) -> impl for<'a> FnMut(&'a [i16]) -> &'a [i16] {
  |             ^^^^^^^^^^
  • The returned function should capture buf by value (ie, use move )返回的 function 应该按值捕获buf (即,使用move
  • The returned function must not outlive buf (having the lifetime 'buf in the below snippet):返回的 function 不得超过buf (在以下代码段中具有生命周期'buf ):

So:所以:

fn fun<'buf>(buf: &'buf mut [f32], mut idx: usize) -> impl FnMut(&[i16]) -> &[i16] + 'buf {
    move |input| {
        buf[idx] = input[0] as f32;
        idx += 1;
        &input[1..]
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM