gpt4 book ai didi

rust - 不能在循环中以可变的形式借用

转载 作者:行者123 更新时间:2023-12-04 17:09:09 24 4
gpt4 key购买 nike

我有 following code :

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

    最佳答案

    这是一个编译器限制 atm。
    您可以重构为:

    pub fn read_packet<'a>(buf: &'a mut [u8]) {
    loop {
    if read_exact(buf) {
    break;
    }
    }
    }


    fn is_packet(a: &[u8]) -> bool {
    true
    }
    fn read_exact<'a>(a: &'a mut [u8]) -> bool {
    is_packet(a)
    }

    fn to_packet<'a>(_: &'a [u8]) -> Option<&'a [u8]> {
    todo!()
    }

    fn process_packet<'a>(buf: &'a mut [u8]) {
    read_packet(buf);
    let _packet = to_packet(buf);
    }
    Playground

    关于rust - 不能在循环中以可变的形式借用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69850238/

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