I'm working my way through the beginner's tutorial and I have a question about threads. How can I pass a thread to a file in the '/src' folder?
My modified mspc::channel example:
main.rs:
use std::sync::mpsc;
use std::thread;
mod Producer;
fn main() {
let (transmit, receive) = mpsc::channel();
thread::spawn(move || {
Producer::transmitter(&transmit);
});
let received = receive.recv().unwrap();
println!("Got {}", received);
}
Producer.rs
use std::sync::mpsc::Sender;
use std::thread;
pub fn transmitter(transmit: &Sender<T>) {
let val = String::from("Hi");
transmit.send(val).unwrap();
}
What do you mean "pass a thread to a file"? Source files don't exist at runtime, they are a compile-time abstraction. What are you trying to do? What problem are you trying to solve?
I want separate the Producer thread from the main.rs like I would do that in other languages.
Error message:
error[E0282]: type annotations needed for (Sender<T>, std::sync::mpsc::Receiver<T>)
--> src/main.rs:11:6
|
7 | let (transmit, receive) = mpsc::channel();
| ------------------- consider giving this pattern the explicit type (Sender<T>, std::sync::mpsc::Receiver<T>), with the type parameters specified
...
11 | let received = receive.recv().expect("Could not receive anything.");
| ^^^^^^^^ cannot infer type
error: aborting due to 2 previous errors; 1 warning emitted
Regarding the error, you need to specify the message type in the argument.
use std::sync::mpsc::Sender;
use std::thread;
pub fn transmitter(transmit: &Sender<String>) {
let val = String::from("Hi");
transmit.send(val).unwrap();
}
Please put error messages in code blocks like you did with the code snippets. Note that if you make the code block by surrounding the code with ``` rather than by indenting with four spaces, you get syntax highlighting.