Poperton
Poperton

Reputation: 2206

How to move struct only one inside a loop

I have a simple fifo that has a method push_back_or_wait. It tries to push_back an element to the fifo in a while loop until it succeeds:

while encoded_packets_fifo
    .push_back_or_wait(
        encoded_packet,
        defaults::default_timeout_stoppable
    ).is_none()
    {
        // ...
    }

the function:

pub fn push_back_or_wait(&mut self, t: T, timeout: Duration) -> Option<()> {
    self.0.push_back_or_wait(t, timeout)
}

The problem is that encoded_packet: EncodedPacket is a simple struct that is expensive to copy. However I can't send a reference instead of moving encoded_packet, because self.0.push_back_or_wait requires a move (to store in a fifo, of course).

The problem is that if I try to move it, I get:

use of moved value: `encoded_packet`

value moved here, in previous iteration of looprustc(E0382)
bitstream_rtsp_client.rs(91, 25): move occurs because `encoded_packet` has type `common::encoded_packet::EncodedPacket`, which does not implement the `Copy` trait

However I clearly only use this once in the iteration, which stops when it successfully sent, so I should be able to move only once.

How can I move only once and then stop the iteration?

Upvotes: 0

Views: 360

Answers (1)

NovaDenizen
NovaDenizen

Reputation: 5325

If it's expensive to copy it, stop copying it. Every move is essentially a copy. Put Rc<EncodedPacket> in the fifo instead.

Upvotes: 2

Related Questions