[英]How to use Higher Rank Trait Bounds with anonymous closure in return type
是否可以返回帶有引用的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..]
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.