gpt4 book ai didi

rust - 无法推断包含对闭包的引用的结构的生命周期

转载 作者:行者123 更新时间:2023-11-29 08:18:40 25 4
gpt4 key购买 nike

<分区>

我正在尝试编译我的代码的这个简化和独立版本:

struct FragMsgReceiver<'a, 'b: 'a> {
recv_dgram: &'a mut FnMut(&mut [u8]) -> Result<&'b mut [u8], ()>,
}

impl<'a, 'b> FragMsgReceiver<'a, 'b> {
fn new(
recv_dgram: &'a mut FnMut(&mut [u8])
-> Result<&'b mut [u8], ()>
) -> Self {
FragMsgReceiver { recv_dgram }
}
}

fn main() {
let recv_dgram = |buff: &mut [u8]| Ok(buff);
let fmr = FragMsgReceiver::new(&mut recv_dgram);
}

这里是错误:

error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
--> src/main.rs:15:43
|
15 | let recv_dgram = |buff: &mut [u8]| Ok(buff);
| ^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime #2 defined on the body at 15:22...
--> src/main.rs:15:22
|
15 | let recv_dgram = |buff: &mut [u8]| Ok(buff);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^
note: ...so that expression is assignable (expected &mut [u8], found &mut [u8])
--> src/main.rs:15:43
|
15 | let recv_dgram = |buff: &mut [u8]| Ok(buff);
| ^^^^
note: but, the lifetime must be valid for the block suffix following statement 1 at 16:53...
--> src/main.rs:16:53
|
16 | let fmr = FragMsgReceiver::new(&mut recv_dgram);
| _____________________________________________________^
17 | | }
| |_^
note: ...so that variable is valid at time of its declaration
--> src/main.rs:16:9
|
16 | let fmr = FragMsgReceiver::new(&mut recv_dgram);
| ^^^

据我从错误消息中了解到,编译器不理解 buff 引用(recv_dgram 的参数)实际上可以比recv_dgram。不过我可能是错的。

为了提供一些上下文,我正在尝试创建一个包装 Rust Tokio UDP 套接字的结构。为此,我引用了函数 recv_dgram。在我的原始代码中,此函数将缓冲区作为参数,并返回一个 Future。当 Future 就绪时,缓冲区将被填充。 Future 的项目还包含发送者的地址和写入缓冲区的字节数。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com