Forward-Discard with a thread ring

I'm trying to implements the forward/discard principle in a ring of threads.
In the end I want the threads to know the entire "network" and how far each node is from each other.
I have almost everything initialized but there is a missing bit, here the code.

use std::sync::mpsc::{self, Receiver, Sender};

struct Ring<T> {
    nodes: Vec<Node<T>>,
}

struct Node<T> {
    tx_left: Sender<T>,
    rx_left: Receiver<T>,
    tx_right: Sender<T>,
    rx_right: Receiver<T>,
}

fn main() {
    let size = 10;
    let mut ring: Ring<&str> = Ring {
        nodes: Vec::with_capacity(size),
    };

    let (junction_tx_left, junction_rx_right) = mpsc::channel();
    let (junction_tx_right, junction_rx_left) = mpsc::channel();
    let mut previous_right_tx = junction_tx_right;
    let mut previous_right_rx = junction_rx_right;

    for i in 0..size {
        let (tx_left, rx_right) = mpsc::channel();
        let (tx_right, rx_left) = mpsc::channel();
        ring.nodes.push(Node {
            tx_left,
            rx_left,
            tx_right: previous_right_tx,
            rx_right: previous_right_rx,
        });

        if i + 1 == size - 1 {
            previous_right_tx = junction_tx_left; // I can clone this to fix the problem
            previous_right_rx = junction_rx_left; // I cannot clone a receiver this is the biggest problem
        } else {
            previous_right_tx = tx_right;
            previous_right_rx = rx_right;
        }
    }
}

As you can see the lines with the comments are the problem, that branch is going to be execute only once but the compiler doesn't know/care about that. Do you know a way, how I can fix it?

I don't want to use Option because the struct is fully initialized at the start and it doesn't seem right to use it for me.

This is just an exercise, right now there is not a specific problem I need to solve other than the initialization.

Thanks :slight_smile:

If you use the crossbeam channel, then you can clone the receiver.

Thanks :slight_smile:

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.