send and recv
- Rust course
- Advanced
- Lesson 20/81
- 4 min
Send and receive messages with send and recv.
send and recv
Both operations can report that the other side has closed:
tx.send(v)returnsErr(SendError(v))if the receiver was dropped, giving the value back.rx.recv()waits until a message arrives; if all senders were dropped and the channel is empty, it returnsErr(RecvError).
let (tx, rx) = mpsc::channel::<i32>();
drop(rx);
println!("{}", tx.send(1).is_err()); // true: nobody is listeningThese errors are the clean way for one thread to learn that the other has finished.
Handling closure
A worker should stop quietly when the main thread closes:
thread::spawn(move || loop {
let veri = hesapla();
if tx.send(veri).is_err() {
break; // the receiver is gone, stop working
}
});On the recv side, the pattern while let Ok(m) = rx.recv() does the same job.
Practice Closure errors
Drop the receiver of one channel and print the result of send(1).is_err(). Drop the sender of another channel and print the result of recv() with {:?}.
Starter code
use std::sync::mpsc;
fn main() {
// buraya yaz
}Sample solution
use std::sync::mpsc;
fn main() {
let (tx, rx) = mpsc::channel::<i32>();
drop(rx);
println!("{}", tx.send(1).is_err());
let (tx2, rx2) = mpsc::channel::<i32>();
drop(tx2);
println!("{:?}", rx2.recv());
}Expected output
true Err(RecvError)
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Why does <code>send</code> give the value back on error?
- Convention
- It doesn't
- So the value isn't lost; it can be sent elsewhere or saved Correct answer
- To prevent memory leaks
Explanation: The value is reachable again via SendError(v).0.
2 Is the receiver closed?
if tx.send(veri).____() {
break;
}
if tx.send(veri).is_err() {
break;
}
Explanation: send returns Err if there's no receiver.
3 Case and result
| Term | Meaning |
|---|---|
rx dropped + send |
Err(SendError(v)) |
tx dropped + recv (empty) |
Err(RecvError) |
Message present + recv |
Ok(message) |
while let Ok(m) = rx.recv() |
Ends on close |