我有以下代码
:
pub fn read_packet<'a>(buf: &'a mut [u8]) -> &'a [u8] {
loop {
read_exact(buf);
if let Some(packet) = to_packet(buf) {
return packet;
}
}
}
fn read_exact(_: &mut [u8]) {
todo!()
}
fn to_packet<'a>(_: &'a [u8]) -> Option<&'a [u8]> {
todo!()
}
我遇到了如下错误:
error[E0502]: cannot borrow `*buf` as mutable because it is also borrowed as immutable
--> src/lib.rs:3:9
|
1 | pub fn read_packet<'a>(buf: &'a mut [u8]) -> &'a [u8] {
| -- lifetime `'a` defined here
2 | loop {
3 | read_exact(buf);
| ^^^^^^^^^^^^^^^ mutable borrow occurs here
4 |
5 | if let Some(packet) = to_packet(buf) {
| --- immutable borrow occurs here
6 | return packet;
| ------ returning this value requires that `*buf` is borrowed for `'a`
我认为这应该是可行的,因为:
read_exact
中的可变借用在第 3 行完成。- 如果
to_packet
返回Some
,则将该值返回给调用方。 - 如果没有,则对
to_packet
的不可变借用在循环结束时结束。因此,在下一次迭代中可以自由地进行可变借用。
有人能告诉我为什么这不起作用吗?
编辑:
这似乎是当前借用检查器的限制。我尝试在夜间使用 Polonius 它可以正常工作。
RUSTFLAGS=-Zpolonius cargo +nightly check