November 2017
Intermediate to advanced
264 pages
5h 45m
English
Which datatypes can be sent over a channel? Rust requires that data to be sent over a channel must implement the Send trait, which guarantees that ownership is transferred safely between threads. Data that does not implement Send cannot leave the current thread. An i32 is Send because we can make a copy, so let's do that in the following code snippet:
fn main() {
let (tx, rx) = channel();
thread::spawn(move|| {
tx.send(10).unwrap();
});
let res = rx.recv().unwrap();
println!("{:?}", res);
}
This of course prints 10.
Here, tx is moved inside the closure. A better way to write tx.send(10).unwrap() is the following:
tx.send(10).ok().expect("Unable to send message");
This will ensure that, in the case of a problem, ...
Read now
Unlock full access