So I'm going through some tutorials and as always trying to make my own versions of the code to work (in order to better understand the things I am learning). This time I wanted to create a simple message-based communication over a channel. In the example below if I put everything into main () as demonstrated , everything works
use std::sync::mpsc::channel;
use std::thread;
use std::time::Duration;
fn main() {
let (send, recv) = channel();
thread::spawn(move || {
send.send("Hello there!".to_string()).unwrap();
loop {
thread::sleep(Duration::from_secs(3));
send.send("Delayed for 3 seconds".to_string()).unwrap();
}
});
loop {
println!("{}", recv.recv().unwrap());
}
}
But if I want to create an object from it (as in the example below), i get a different problem on every fix I make:
use std::sync::mpsc::{channel, Receiver, Sender};
use std::thread;
use std::time::Duration;
#[derive(Clone)]
struct Obj {
send: Sender<String>,
recv: Receiver<String>,
}
impl Obj {
fn new() -> Self {
let (send, recv) = channel();
Obj {
send: send,
recv: recv,
}
}
fn listen(self) {
loop {
println!("{}", self.recv.recv().unwrap());
}
}
fn brodcast(self) {
let x = self.send.clone();
thread::spawn(move || {
x.send("Hello there!".to_string()).unwrap();
loop {
thread::sleep(Duration::from_secs(3));
x.send("Delayed for 3 seconds".to_string()).unwrap();
}
});
}
}
fn main() {
let obj = Obj::new();
obj.brodcast();
// do some stuff here
obj.listen();
}
So finally I gave up and decided to post my problem here seeking your advice. Could someone please take a look at it and give pointers on what to do to make it work
Thnx