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

问题描述

是否可以返回 FnMut 闭包,它接受引用并返回具有相同生命周期的引用?

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