【问题标题】:`variable` was mutably borrowed here in the previous iteration of the loop`variable` 在循环的前一次迭代中被可变地借用在这里
【发布时间】:2023-01-10 16:50:05
【问题描述】:

我是 Rust 的新手,我一直在尝试解决代码中的错误。

下面的代码编译。然而,如果我取消注释行以将数据包添加到我的缓冲区,它会抛出错误:

`interface` was mutably borrowed here in the previous iteration of the loop

如何?那时它与数据包完全无关。我以为我开始掌握引用和内存管理概念,但这让我第二次猜测一切......

        let mut buffer: VecDeque<pcap::Packet> = VecDeque::with_capacity(1000);
        while let Ok(packet) = interface.next_packet() {
            if start_time.is_none() {
                start_time = Some(Instant::now());
            }

            let buf_packet = packet.to_owned();

            // buffer.push_back(buf_packet);

            let elapsed = start_time.unwrap().elapsed();
            if elapsed >= time_limit {
                break;
            }
        }

【问题讨论】:

  • edit你的问题并提供minimal reproducible example这个sn-p代码不是我们可以帮助你调试的东西。这可能是当前借用检查器的限制。
  • 看起来 pcap::Packet 有与之关联的生命周期。所以 .to_owned() 不会将它与原始来源分离。

标签: rust pcap


【解决方案1】:

Packet 没有拥有的变体。 to_owned() 来自blanket ToOwned implementation in the standard library,它适用于任何实现Clone 的东西。奇怪的是,这种类型实现了Clone,而不是Copy

无论如何,Packet 只持有两个引用。克隆会复制这些引用,因此这实际上对借用或它们的生命周期没有任何意义。

相反,考虑实现您自己的拥有自己数据的“拥有的数据包”类型:

struct OwnedPacket {
    pub header: PacketHeader,
    pub data: Vec<u8>,
}

impl<'a> From<Packet<'a>> for OwnedPacket {
    fn from(other: Packet<'a>) -> Self {
        Self {
            header: *other.header,
            data: other.data.into(),
        }
    }
}

现在你可以将你的双端队列更改为VecDeque&lt;OwnedPacket&gt;,并在推送数据包时调用packet.into()来执行复制。

【讨论】:

    猜你喜欢
    • 2021-05-15
    • 1970-01-01
    • 2021-05-15
    • 2023-04-10
    • 2021-12-08
    • 2020-03-03
    • 2021-05-22
    • 1970-01-01
    • 2021-01-21
    相关资源
    最近更新 更多