如何在 return 类型中使用带有匿名闭包的高阶特征边界

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

是否有可能 return FnMut 引用的闭包和 return 具有相同生命周期的引用?

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

我已经尝试过 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] {
  |             ^^^^^^^^^^
  • 返回的函数应该按值捕获 buf(即使用 move
  • 返回的函数不能超过 buf(在下面的代码片段中具有生命周期 'buf):

所以:

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..]
    }
}